我正在尝试使用反射从类中获取属性。这是我所看到的一些示例代码:
using System.Reflection;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
PropertyInfo[] tmp2 = typeof(TestClass).GetProperties();
PropertyInfo test = typeof(TestClass).GetProperty(
"TestProp", BindingFlags.Public | BindingFlags.NonPublic);
}
}
public class TestClass
{
public Int32 TestProp
{
get;
set;
}
}
}
当我追踪它时,这就是我所看到的:
- 当我使用 获取所有属性
GetProperties()
时,生成的数组有一个条目,用于 propertyTestProp
。 - 当我尝试使用 获取时
TestProp
,GetProperty()
我得到了 null 回来。
我有点难过;我无法在 MSDN 中找到任何有关GetProperty()
向我解释此结果的内容。有什么帮助吗?
编辑:
如果我添加BindingFlags.Instance
到GetProperties()
通话中,则找不到任何属性,句号。这更加一致,并且让我相信TestProp
由于某种原因它不被视为实例属性。
为什么会这样?我需要对该类做什么才能将此属性视为实例属性?