【发布时间】:2010-09-26 12:02:40
【问题描述】:
我正在尝试使用反射从类中获取属性。这是我所看到的一些示例代码:
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()获取所有属性时,生成的数组有一个条目,用于属性TestProp。 - 当我尝试使用
GetProperty()获取TestProp时,我返回 null。
我有点难过;我在 MSDN 中找不到任何关于 GetProperty() 的内容来向我解释这个结果。有什么帮助吗?
编辑:
如果我将BindingFlags.Instance 添加到GetProperties() 调用中,则找不到任何属性,句号。这更加一致,并让我相信 TestProp 由于某种原因不被视为实例属性。
为什么会这样?我需要对该类执行什么操作才能将此属性视为实例属性?
【问题讨论】:
标签: c# reflection properties