If there are various animals, such as dogs/cats/cows /..., there are different age methods. If you want to use the same showage method from the base class to display these different age, you can naturally borrow the virtual function of the base class animal, for example:
public class Animal{ public virtual Age { get {....} set {....} } public ShowAge() { Show(Age); }}public class Dog : Animal{ public override Age { get {...} set {...} }}public class Cat : Animal{ public override Age { get {...} set {...} }
Override is critical, because if there is no override, animal will call its own age. If dog and cat are a class automatically generated by LINQ/EF, there is no override keyword. This happens.
Of course, it cannot be manually added to the Code generated by LINQ/ef each time. What should I do?
The last time I encountered this problem, I had to search for it. After testing for half a day, I found a way to use it again today. It seems that post sharing is not uncommon.
In animal, use the following code:
public virtual int Age { get { PropertyInfo pi = this.GetType().GetProperty("Age"); int age = (int)pi.GetValue(this, new object[] {}); return age; } set { PropertyInfo pi = this.GetType().GetProperty("Age"); pi.SetValue(this, value, new object[] { }); } }
In fact, this method has nothing to do with "inheritance". It simply reads the attributes in the database table and can respond to emergencies.
Click to download the free agile development textbook: Martian agile development manual