我有2个班级:
public class Access
{
public class Job
{
public int Id { get; set; }
protected string JobName { get; set; }
}
}
Class2.cs
public class Full: Access.Job
{
}
Full ful = new Full();
为什么我无法访问ful.JobName
成员?
答案 0 :(得分:5)
因为您正在尝试从类外部访问受保护的方法。只有公共方法可用。您可以访问受保护的属性/ variably /方法,仅在继承的类中,但不能从外部代码访问:
public class Full: Access.Job
{
public void mVoid()
{
Console.WriteLine(this.JobName);
}
protected void mProtVoid()
{
Console.WriteLine(this.JobName);
}
private void mPrivateVoid()
{
Console.WriteLine("Hey");
}
}
Full myFull = new Full();
myFull.mVoid(); //will work
myFull.mProtVoid(); //Will not work
myFull.mPrivateVoid(); //Will not work
如果您需要访问受保护的属性,有两种方法(实际上有3种方式,但反射是肮脏的方式,应该避免):
<强> 1。公开
如果它将设置为public,则它将是stil继承,您可以直接访问它:
Full nFull = new Full();
Console.Write(nFull.JobName);
<强> 2。制作一个“包装”/“外观”
创建新属性或方法,只访问隐藏属性并以预期格式返回。
public class Full: Access.Job
{
public string WrappedJobName { get { return this.JobName; } }
public string WrappedJobName => this.JobName; //C# 6.0 syntax
}
Full mFull = new Full();
Console.WriteLine(mFull.WrappedJobName);