简体   繁体   中英

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> . In my Iteration (foreach), I have to implement the the derived class to do computation (sample computation - addition). 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM