我有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
会员?
因为您正在尝试从类外部访问受保护的方法.只有公共方法可用.您可以访问受保护的属性/ 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);