14

我正在尝试使用反射从类中获取属性。这是我所看到的一些示例代码:


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()时,生成的数组有一个条目,用于 property TestProp
  • 当我尝试使用 获取时TestPropGetProperty()我得到了 null 回来。

我有点难过;我无法在 MSDN 中找到任何有关GetProperty()向我解释此结果的内容。有什么帮助吗?

编辑:

如果我添加BindingFlags.InstanceGetProperties()通话中,则找不到任何属性,句号。这更加一致,并且让我相信TestProp由于某种原因它不被视为实例属性。

为什么会这样?我需要对该类做什么才能将此属性视为实例属性?

4

3 回答 3

13

添加BindingFlags.InstanceGetProperty通话中。

编辑:回应评论......

以下代码返回该属性。

注意:在您尝试检索它之前实际让您的属性做一些事情是个好主意(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
            {
            }
        }
    }
}
于 2008-12-11T18:46:36.293 回答
1

尝试添加以下标签:

System.Reflection.BindingFlags.Instance

编辑:这有效(至少对我来说)

PropertyInfo test = typeof(TestClass).GetProperty("TestProp", BindingFlags.Public | BindingFlags.Instance);

Console.WriteLine(test.Name);
于 2008-12-11T18:48:56.773 回答
0

您还需要指定它是静态的还是实例(或两者)。

于 2008-12-11T18:46:41.490 回答