Say I have a Father class to be inherited by Children classes, later I want to add more stuff into the Father class without modifying the original Father class, please teach me how could I do it.
Let me clarify my question. Any valuables and methods in Father will automatically accessible to all the Children classes, right? For example:
public class Father
{
public int a;
public int b;
public int c()
{
return a+b;
}
}
public class Child : Father
{
private int d=a*b+c();
}
Now I want to add a boolean e and a method f() to Father so my Child could access it directly, without adding those lines directly in Father or make a new class in between Father and Child. Is that possible? How could I do it?
You are looking for Extension Methods. Refer this post for more information.
If you want to add more fields to your father model then maybe your inheritance structure should be changed.
For example you had model A and model B. Model B inherited fields from model A
This way the class B has fields
FieldA
andFieldB
.Now if you want your class B to inherit from a class that has the fields of A but more you could add another layer to your inheritance tree like this.
Now your class B has fields
FieldA
andFieldB
andFieldC
and you don't have to alter your original father class A.Now if you want to extend methods for a class you could also go with static extensions like this:
and then call
A.DoSomething();