c# - 内部 protected 属性(property)仍然可以从不同的程序集访问

标签 c# .net

我正在为有关辅助功能的初学者 session 设置一些演示代码,我发现我能够从派生类访问内部 protected 属性。我错过了什么?

程序集 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();
        }
    }
}

程序集 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);
        }
    }
}

在 ExampleClass.Go 中注意我可以为 Prop5 设置一个值。为什么?它被标记为内部保护,但我无法在 Prop4 上设置值(标记为内部)

最佳答案

internal protected 表示“程序集内部或继承类”。所以是的,如果你有一个带有 protected 内部成员的公共(public)类,另一个在不同程序集中继承该类型的类仍然可以访问它,因为 protected 修饰符:

protected internal

The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

引用:http://msdn.microsoft.com/en-us/library/ms173121.aspx

这是 C# 语言的限制。 CLR 支持“Internal AND Protected”概念。 MethodAttributes.FamANDAssem 证明了这一点如果您要发出自己的 IL,请枚举。如果您真的想要此功能,您可以使用诸如 Mono.Cecil 之类的东西进行一些 IL 后处理。为什么 C# 语言不公开这只是一个猜测:几乎不需要它。

关于c# - 内部 protected 属性(property)仍然可以从不同的程序集访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7000871/

相关文章:

c# - 二叉搜索树遍历 - PreOrder

.net - 无法从 Emgucv 中的文件创建捕获

.NET 和动态语言

.net - 崩溃时重新启动应用程序

c# - Generic Repository 是否需要一个 Base Entity 类才能在所有地方应用?

c# - 如何将字符串反序列化为类?

c# - 为 ComboBox 设置默认值

c# - 扫描 QR 码 (vcard) 并在 windows phone 7 上保存联系人

c# - System.Reflection - 如何调用子级别类型的 getter 方法?

c# - 区分子类和父类对象?