什么是从嵌套类的封闭类访问领域的最佳途径? [英] What's the best way of accessing field in the enclosing class from the nested class?
问题描述
说,如果我有一个形式的下拉菜单,我有这个类里面又嵌套类。
现在,什么是从嵌套类访问此下拉列表的最佳方式?
Say if I have a dropdown in a form and I have another nested class inside of this class . Now what's the best way to access this dropdown from the nested class?
推荐答案
与Java,嵌套类是不是一个特殊的内部类,所以你需要传递一个参考。雷蒙德陈有在这里描述的差别的例子: C#嵌套类像C ++嵌套类,不的Java内部类。
Unlike Java, a nested class isn't a special "inner class" so you'd need to pass a reference. Raymond Chen has an example describing the differences here : C# nested classes are like C++ nested classes, not Java inner classes.
这里是嵌套类的构造函数传递,供日后参考外部类的实例的实例。
Here is an example where the constructor of the nested class is passed the instance of the outer class for later reference.
// C#
class OuterClass
{
string s;
// ...
class InnerClass
{
OuterClass o_;
public InnerClass(OuterClass o) { o_ = o; }
public string GetOuterString() { return o_.s; }
}
void SomeFunction() {
InnerClass i = new InnerClass(this);
i.GetOuterString();
}
}
请注意,将InnerClass可以访问取值
的OuterClass,我没有修改雷蒙德code(我挂以上),所以记得该字符串s;
是私人
,因为没有指定其他访问权限。
Note that the InnerClass can access the "s
" of the OuterClass, I didn't modify Raymond's code (as I linked to above), so remember that the "string s;
" is private
because no other access permission was specified.
这篇关于什么是从嵌套类的封闭类访问领域的最佳途径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!