我有三个类,其中两个继承自一个基类,第三个类根据应用程序的状态,我希望引用另外两个类中的一个。
有时我需要实例化Child1,有时需要Child2。然而,我有一个模型想要在应用程序中传递以保持一切在一个地方,但我希望使持有Child1和Child2的属性通用化,例如:
public class Batch
{
public Batch() { }
}
public class RequestBatch : Batch
{
public RequestBatch(string batchJobType) : base(batchJobType) { }
public override int RecordCount
{
get { return Lines.Count; }
}
}
public class ResponseBatch : Batch
{
public ResponseBatch(string batchJobType) : base(batchJobType) { }
public ResponseBatch(int BatchJobRunID)
{ }
}
有时我需要实例化Child1,有时需要Child2。然而,我有一个模型想要在应用程序中传递以保持一切在一个地方,但我希望使持有Child1和Child2的属性通用化,例如:
public class BatchJob {
public List<Batch> Batches { get; set; }
}
然后稍后这样做
public List<RequestBatch> GetBatches(...) {}
var BatchJob = new BatchJob();
BatchJob.Batches = GetBatches(...);
然而,编译器告诉我它无法隐式将 Child1 转换为(其基类型)Parent。
在“= GetBatches(...”下出现红色下划线,表示“无法隐式转换类型 'System.Collections.Generic.List' 为 'System.Collections.Generic.List'”
有没有一种方法可以使属性通用化,以便它可以接受任何抽象类型的 Parent?
谢谢!
class BaseClass { public void MethodA() { Console.WriteLine("BaseClass"); } } class DerivedClass : BaseClass { public void MethodB() { Console.WriteLine("DerivedClass"); } } // 隐式地将DerivedClass实例转换为BaseClass实例 DerivedClass derived = new DerivedClass(); BaseClass baseClass = derived; // 调用基类方法 baseClass.MethodA(); // Output: "BaseClass" // 无法调用派生类方法 // baseClass.MethodB(); // 编译错误!
在上面的示例中,DerivedClass
是BaseClass
的子类,并且可以隐式地转换为BaseClass
类型。虽然转换后的实例仍然是DerivedClass
类型,但只能访问BaseClass
定义的成员。因此,对于baseClass
实例,只能调用MethodA
而不能调用MethodB
。 - SLaks