首页 > 解决方案 > Conditional inheritance: base class depend on environment variable

问题描述

I have two abstracts classes, 'ValidationsWithStorage' inherits 'Validations'

   public abstract class Validations {
    // methods..
   }

   public abstract class ValidationsWithStorage : Validations { 
    // ... 
    }

I also have a class:

public abstract class TestsValidations : T

T should be depend on the environment variable:

Environment.GetEnvironmentVariable("useStorage") 

If this variable is null I want that T will be Validations. Else, I want that T will be ValidationsWithStorage.

What is the best way to do it?

Thanks

标签: c#inheritanceabstract-class

解决方案


我不认为你可以按照你的方式做你想做的事。

为什么不让您的类TestValidations在其构造函数中使用类型ValidationsValidationsWithStorage. 如果它们都遵循相同的接口,那么您的TestsValidations类就不需要知道(或关心)它正在使用的两者中的哪一个。

所以基本上:

  1. Validations为您和ValidationsWithStorage班级创建一个界面
  2. 检查您的环境变量
  3. TestsValidation根据环境变量将正确的类传入构造函数

这有帮助吗?


推荐阅读