派生类的C#强制转换

时间:2015-03-25 15:50:02

标签: c# inheritance casting polymorphism

一个菜鸟问题......

我有两个班级,一个是普通的(父母),一个是专门的(孩子)一个:

public abstract class BaseTest
{
   public BaseTestSettings Settings{get;set;}
   public abstract void Run();
}

public class BaseTestSettings
{
   public double SettingsProp1{get;set;}
   public double SettingsProp1{get;set;}
}

public class SpecializaedTestSettings : BaseTestSettings
{
   public double SpecializaedTestSettingsPropA{get;set;}
   public double SpecializaedTestSettingsPropB{get;set;}
}

public class SpecializaedTest : BaseTest
{
   public SpecializaedTest()
   {
      this.Settings = new SpecializaedTestSettings();
   }

   public override void Run()
   {
      SpecializaedTestSettings settings = (SpecializaedTestSettings)this.Settings;
   }
}

有没有办法在专门的测试中避免在重写的Run方法中进行强制转换?我想解决方案是在Settings类中定义SpecializedTestSettings类型的SpecializedTest属性,但我的目标是避免这种情况并仅将这些属性声明一次。我想我不能?

1 个答案:

答案 0 :(得分:4)

使用Generics

public abstract class BaseTest<TSettings> where TSettings : BaseTestSettings
{
   public TSettings Settings{get;set;}
   public abstract void Run();
}

public class BaseTestSettings
{
   public double SettingsProp1{get;set;}
   public double SettingsProp1{get;set;}
}

public class SpecializaedTestSettings : BaseTestSettings
{
   public double SpecializaedTestSettingsPropA{get;set;}
   public double SpecializaedTestSettingsPropB{get;set;}
}

public class SpecializaedTest : BaseTest<SpecializaedTestSettings>
{
   public SpecializaedTest()
   {
      this.Settings = new SpecializaedTestSettings();
   }

   public override void Run()
   {
      SpecializaedTestSettings settings = this.Settings;
   }
}

如果您需要非通用/协变版本,则可以编写协变接口或非通用基本类型。