[英]Base class to Derived class in Iteration
I have this base class that has some properties. 我有这个具有一些属性的基类。 In my derived class this is where I wanted to implement some computation (addition and subtraction for example). 在我的派生类中,这是我想要实现一些计算(例如加法和减法)的地方。
I implemented a list of base class. 我实现了一个基类列表。 List<A>
. List<A>
。 In my Iteration (foreach), I have to implement the the derived class to do computation (sample computation - addition). 在我的迭代(foreach)中,我必须实现派生类进行计算(样本计算-加法)。 How can we implement this? 我们如何实现呢? Please let me know if not clear. 如果不清楚,请通知我。
public class A {
public int value1 { get; set;}
public int value2 { get; set;}
public virtual int sum { get { return 0 ;} }
}
public class B : A {
public override int sum {
get {
return value1 + value2;
}
}
}
List<A> collection = new List<A>();
collection.Add(new A { value1 = 1, value2 = 1 });
collection.Add(new A { value1 = 2, value2 = 2 });
collection.Add(new A { value1 = 3, value2 = 3 });
foreach (var item in collection.OfType<B>())
{
Console.WriteLine(item.sum);
}
As mentioned in the comment, just use the following code: 如评论中所述,只需使用以下代码:
List<A> collection = new List<A>();
collection.Add(new B { value1 = 1, value2 = 1 });
collection.Add(new B { value1 = 2, value2 = 2 });
collection.Add(new B { value1 = 3, value2 = 3 });
foreach (var item in collection)
{
Console.WriteLine(item.sum);
}
The sum
method will be resolved at runtime to the method on B
, and everything should work fine. sum
方法将在运行时解析为B
上的方法,并且一切正常。
Just modify this as mentioned in the comment above 只需按照上面的评论中所述修改它
collection.Add(new A { value1 = 1, value2 = 1 });
collection.Add(new A { value1 = 2, value2 = 2 });
collection.Add(new A { value1 = 3, value2 = 3 });
foreach (var item in collection.OfType<B>())
{
Console.WriteLine(item.sum);
}
to this and it should work 为此,它应该工作
collection.Add(new B { value1 = 1, value2 = 1 });
collection.Add(new B { value1 = 2, value2 = 2 });
collection.Add(new B { value1 = 3, value2 = 3 });
foreach (var item in collection)
{
Console.WriteLine(item.sum);
}
That's because in your sample every instance of Type A is just Type A and every instance of Type B is Type B AND Type A. 这是因为在您的示例中,类型A的每个实例都是类型A,类型B的每个实例都是类型B和类型A。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.