namespace PalleTech
{
public class Parent
{
private int test = 123;
public virtual int TestProperty
{
// Notice the accessor accessibility level.
set {
test = value;
}
// No access modifier is used here.
protected get { return test; }
}
}
public class Kid : Parent
{
private int test1 = 123;
public override int TestProperty
{
// Use the same accessibility level as in the overridden accessor.
set { test1 = value / 123; }
// Cannot use access modifier here.
protected get { return 0; }
}
}
public class Demo:Kid
{
public static void Main()
{
Kid k = new Kid();
Console.Write(k.TestProperty);
}
}
}
错误1无法通过“PalleTech.Kid”类型的限定符访问受保护的成员“PalleTech.Parent.TestProperty”;限定符必须是'PalleTech.Demo'类型(或从中派生出来)
答案 0 :(得分:2)
From MSDN Article “只有通过派生类类型进行访问时,才能在派生类中访问基类的受保护成员。”
在这里,您将通过其实例访问Kid的受保护的setter。您必须创建Demo类的实例并通过它进行访问。
答案 1 :(得分:1)
TestProperty
类中Kid
的getter受到保护,这意味着如果您编写一个派生自Kid
类的类,则可以访问TestProperty
;如果您创建Kid
类的实例,则无法访问它。
您可以通过从两个类的setter中删除protected
来更改行为;
public class Parent
{
private int test = 123;
public virtual int TestProperty
{
// Notice the accessor accessibility level.
set
{
test = value;
}
// No access modifier is used here.
get { return test; }
}
}
public class Kid : Parent
{
private int test1 = 123;
public override int TestProperty
{
// Use the same accessibility level as in the overridden accessor.
set { test1 = value / 123; }
// Cannot use access modifier here.
get { return 0; }
}
}
答案 2 :(得分:0)
您必须将评估员设置为受保护。 getter / setter的访问修饰符不能比属性本身更少。