How to add stuff into existing base class in C#?

2019-08-01 16:36发布

问题:

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?

回答1:

You are looking for Extension Methods. Refer this post for more information.



回答2:

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

public class A
{
    public string FieldA { get; set; }
}

public class B : A
{
    public string FieldB { get; set; }
}

This way the class B has fields FieldA and FieldB.

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.

public class A
{
    public string FieldA { get; set; }
}

public class C : A
{
    public string FieldC { get; set; }
}

public class B : C
{
    public string FieldB { get; set; }
}

Now your class B has fields FieldA and FieldB and FieldC 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:

Public static void DoSomething(this A a)
{
    ... 
} 

and then call A.DoSomething();