C# - 内部属性在quickwatch中"可读"但不使用反射?

Lal*_*man 4 c# properties protected access-modifiers internal

我看到"快速监视"窗口可以访问所有属性,而不管库中类的访问限制(内部,受保护,私有),即使在完全不同的应用程序,库和命名空间中引用库也是如此.虽然我没有找到使用"反射"访问这些的方法.我特别想"阅读"(注意 - 只是阅读)程序集的内部属性.如果通过设计"内部"如何工作(在同一命名空间外无法访问),这是不可能的,那么VS.NET中的"快速监视"窗口是如何"读取"的呢?

这是我使用的示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestLib
{
    public class TestInteralProp
    {
        internal string PropertyInternal
        {
            get { return "Internal Property!";  }
        }

        protected string PropertyProtected
        {
            get { return "Protected Property!"; }
        }

        string PropertyPrivate
        {
            get { return "Private Property!"; }
        }

        public string PropertyPublic
        {
            get { return "Public Property!";  }
        }

        protected internal string PropertyProtectedInternal
        {
            get { return "Protected Internal Property!"; }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我为TestInernalProp类创建一个对象时,我可以在quickwatch中看到所有4个属性 -

道具

当我使用反射访问除公共属性(PropertyPublic)之外的任何这些,我得到一个空引用异常.

//this works
propTestObj.GetType().InvokeMember("PropertyPublic", System.Reflection.BindingFlags.GetProperty, null, propTestObj, null);
//this fails (obviously)
propTestObj.GetType().InvokeMember("PropertyInternal", System.Reflection.BindingFlags.GetProperty, null, propTestObj, null);

//this works
propTestObj.GetType().GetProperty("PropertyPublic").GetValue(propTestObj, null);
//this fails again
propTestObj.GetType().GetProperty("PropertyInternal").GetValue(propTestObj, null)
Run Code Online (Sandbox Code Playgroud)

我不清楚"快速观察"如何获得这些权限.

Oli*_*bes 12

使用这些标志

BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
Run Code Online (Sandbox Code Playgroud)

GetProperty此操作不需要该标志.您可能还想添加Static.

注意:您可以将标志组合在一起|,因为它们的整数值是2的幂.看到这个答案.


注意(响应Lalman和shanks对Reflection的安全问题的关注)

总有办法编写糟糕或危险的代码.这取决于你做或不做.反射不是常规的做事方式,而是用于编程特殊工具,如o/r-mappers或分析工具.反思非常强大; 但是,你应该明智地使用它.