如何在C#中的现有基础类中添加内容? [英] How to add stuff into existing base class in C#?

查看:84
本文介绍了如何在C#中的现有基础类中添加内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个教父类要由Children类继承,后来我想在不修改原始教父类的情况下向教父类添加更多内容,请教我该怎么做。



让我澄清我的问题。所有儿童班的父亲都会自动使用任何贵重物品和方法,对吗?例如:

 公共类父亲
{
public int a;
public int b;
public int c()
{
return a + b;
}
}

公共班级子女:父亲
{
private int d = a * b + c();
}

现在我想向父亲添加一个布尔值e和一个方法f()这样我的孩子就可以直接访问它,而无需在父亲中直接添加这些行或在父亲与孩子之间建立新的类。那可能吗?我该怎么办?

解决方案

如果您想向父模型添加更多字段,则可能应该更改继承结构。



例如,您有模型A和模型B。模型B继承了模型A的字段

 公共类A 
{
公共字符串FieldA {get;组; }
}

公共类B:A
{
公共字符串FieldB {get;组; }
}

这样,类B具有字段 FieldA FieldB



现在,如果您想让类B继承自一个具有A的字段,但是您可以像这样在继承树中添加另一层。

 公共类A 
{
公用字串FieldA {取得;组; }
}

公用类别C:A
{
公用字串FieldC {取得;组; }
}

公共类B:C
{
公共字符串FieldB {get;组; }
}

现在,您的班级B具有字段 FieldA FieldB FieldC ,您不必更改原始的父类A。 / p>

现在,如果要扩展类的方法,还可以使用静态扩展,例如:

 公共静态无效值DoSomething(this A a)
{
...
}

然后调用 A.DoSomething();


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?

解决方案

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

这篇关于如何在C#中的现有基础类中添加内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆