我正在尝试使用反射从类中获取属性。这是我所看到的一些示例代码:
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
由于某种原因不被视为实例属性。
为什么会这样?我需要对类做什么才能将此属性视为实例属性?
最佳答案
将 BindingFlags.Instance
添加到 GetProperty
调用中。
编辑:回应评论...
以下代码返回该属性。
注意:在您尝试检索它之前让您的属性实际执行某些操作是个好主意 (VS2005) :)
using System.Reflection;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
PropertyInfo[] tmp2 = typeof(TestClass).GetProperties();
PropertyInfo test = typeof(TestClass).GetProperty(
"TestProp",
BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic);
Console.WriteLine(test.Name);
}
}
public class TestClass
{
public Int32 TestProp
{
get
{
return 0;
}
set
{
}
}
}
}
关于c# - 为什么 GetProperty 找不到它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/360422/