我有一个类继承另一个类的类列表。我希望能够访问父变量,而不必使用引用(使事情更具可读性)。我可以在没有参考的情况下访问父变量吗?
public class MyCode : OtherCode
{
public string label;
public MyCode()
{
label = "somestring";
colour = 5;
Console.WriteLine("colour is: " + colour); // this is ok
List<particle> parts = new List<particle>();
parts.Add(new particle());
}
public class particle //I'd like this class to have access to the parent variables
{
public particle()
{
Console.WriteLine("The colour is: " + colour); // can this be accessed without using a parent reference?
//Console.WriteLine("The label is: " + label); // unaccessable
Console.ReadLine();
}
}
}
public class OtherCode
{
public int colour = 1;
public OtherCode()
{
//I didn't do it
}
}
是否有可能继承父变量这种方式,所以我可以用手把它“是”在粒子的方法呢?
为这个令人困惑的例子道歉,我想我因为在这种情况下可以使用继承而松了口气。 我想知道是否可以让嵌套类(粒子)有权访问标签和颜色在施工中传递参考文献并在全国各地使用Parent.variable
?
'粒子'不是'咖啡',因此它不应该有'风味'或任何一个概念,要么做一个界面,要么让'杯子'有'味道'(尽管我不是确定一个杯子是美味的) – Sayse
你正在使用继承错误,就像@Sayse提到的(继承意味着“is-a”,咖啡肯定是地狱不是杯子),你的问题还不清楚。解释你想看到发生的事情,而不是“让更多的可读性”。 – CodeCaster
对不起,但我认为你有些事情倒退了。 “咖啡:杯子”并不是说没有杯子就没有咖啡。因为没有杯子就可以喝咖啡。你说这个的方式说咖啡是一种特定的杯子。它不是。 Cappucino是一种咖啡,一种杯子可以翻译成“Cappucion:Coffee”和“Mug:Cup”。 所以我认为你应该解决这个问题,并在整个OOP阅读,然后你的问题的答案会来找你:) –