繁体   English   中英

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

[英]C# - Internal Properties “readable” in quickwatch but not using reflection?

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

当我为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)

我不清楚“快速观察”如何获得这些权限。

使用这些标志

BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance

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

注意:您可以将标志与| ,因为它们的整数值是2的幂。 看到这个答案


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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM