我需要在我的应用程序中创建同一个类的多个实例。 在这个类中,我需要访问其他类的属性,并且我不想在我的所有类中构建属性。为什么不继承使用值?
所以我想我可以让这个类继承父母,它具有我需要的所有属性。
例如:
// This class is called only once at the start of my app
class Parent
{
int Property1 = 0;
public Parent(int val)
{
this.Property1 = val;
}
}
class Child : Parent
{
public Child()
{
}
public void PrintProp()
{
// Will always print the value of Parent's Property1 which has been defined only once
Console.WriteLine(Property1);
}
}
问题与该代码是,每次我定义了一个新的儿童(),Property1值是0,而不是我把它在我的程序启动时的值。
我该如何做到这一点?
这听起来像'Parent'应该保持某种配置。如果是这样的话,只需在每个子项目中传递该类型的实例即可。继承不会对你有所帮助。 – poke
是所有实例的全局属性1,还是每个实例化的对象都不同? – BlackICE
“孩子”如何知道其父母是“父母”? –