无法访问派生类中的变量 [英] Cannot access variable in derived class
本文介绍了无法访问派生类中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法在派生类中访问i
. m.i
不起作用.为什么?
I am not able to access i
in my derived class. m.i
is not working. Why?
public class MyClass
{
protected int i;
public MyClass()
{
}
public virtual void Display()
{
Console.WriteLine("Base dis");
}
}
public class MyCla : MyClass
{
public MyCla()
{
}
int ij = 12;
public new void Display()
{
MyClass m = new MyClass();
// m.i is inaccessible here
Console.WriteLine("Derived dis");
}
}
推荐答案
这是因为protected
变量和属性仅可用于派生类,在派生上下文中(因此通过使用this
引用)和当前类的实例(因此,如果m
是MyCla
则可以使用).
That is because protected
variables and properties are only available to derived classes, within the derived context (thus by referencing it with this
), and to instances of the current class (so if m
was MyCla
it would have worked).
MyCla m = new MyCla();
int x = m.i;
一个选项是使字段internal
或protected internal
(如果需要),从而使其对于程序集中的所有类均可用.
An option is to make the field internal
, or protected internal
if you wish, which makes it available to all classes within the assembly.
这是一个编译示例.
这篇关于无法访问派生类中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文