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

被刻印的时光 ゝ 提交于 2019-12-11 05:32:59

问题


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();



来源:https://stackoverflow.com/questions/47282089/how-to-add-stuff-into-existing-base-class-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!