Tôi đang thiết lập một số mã demo cho phiên mới bắt đầu về khả năng truy cập và tôi thấy rằng tôi có thể truy cập một thuộc tính được bảo vệ nội bộ từ một lớp dẫn xuất. Tôi đang thiếu gì?thuộc tính được bảo vệ nội bộ vẫn có thể truy cập từ một assembly khác nhau
hội 1
namespace Accessibility
{
class Program
{
static void Main(string[] args)
{
ExampleClass c = new ExampleClass();
c.Go();
//c.Prop1 = 10;
}
}
class ExampleClass : DerivedClass
{
public void Go()
{
this.Prop1 = 10;
this.Prop2 = 10;
//this.Prop3 = 10; //Doesn't work
//this.Prop4 = 10; //Doesn't work
this.Prop5 = 10; //why does this work?!
this.DoSomething();
}
}
}
hội 2
namespace Accessibility.Models
{
public class BaseClass
{
public int Prop1 { get; set; }
protected int Prop2 { get; set; }
private int Prop3 { get; set; }
internal int Prop4 { get; set; }
internal protected int Prop5 { get; set; }
//internal public int Prop6 { get; set; } //Invalid
//internal private int Prop7 { get; set; } //Invalid
public BaseClass()
{
this.Prop3 = 27;
}
}
public class DerivedClass : BaseClass
{
public void DoSomething()
{
this.Prop1 = 10;
this.Prop2 = 10;
//this.Prop3 = 10; //Doesn't work
this.Prop4 = 10;
this.Prop5 = 10;
PropertyInfo Prop3pi = typeof(DerivedClass).GetProperty("Prop3", BindingFlags.Instance | BindingFlags.NonPublic);
int value = (int)Prop3pi.GetValue(this, null);
}
}
}
Lưu ý trong ExampleClass.Go tôi có thể đặt một giá trị để Prop5. Tại sao? Nó được đánh dấu là bảo vệ nội bộ nhưng tôi không thể đặt giá trị trên Prop4 (được đánh dấu là nội bộ)
Vì đó là * nội bộ * HOẶC * được bảo vệ *. Không VÀ. –
-1: Rõ ràng, một tìm kiếm đơn giản trên google sẽ trả lời câu hỏi này ... –
Tôi không nghĩ đó là HOẶC –