我看到“快速监视”窗口可以访问所有属性,无论库中类的访问限制(内部、受保护、私有)如何,即使在完全不同的应用程序、库和命名空间中引用该库也是如此。然而我没有找到使用“反射”访问这些的方法。我特别尝试“读取”(注意 - 只是读取)程序集的内部属性。如果通过“内部”工作方式的设计不可能做到这一点(在同一名称空间之外无法访问),那么为什么它会被 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)
我不清楚“快速观看”如何访问这些内容。