代码之家  ›  专栏  ›  技术社区  ›  Remi Despres-Smyth

为什么getproperty找不到它?

  •  14
  • Remi Despres-Smyth  · 技术社区  · 17 年前

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

    
    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() ,我得到空值。

    我有点为难;我还没有在msdn中找到任何关于 GET属性() 向我解释这个结果。有什么帮助吗?

    编辑:

    如果我添加 BindingFlags.Instance 获取属性() 调用,未找到属性,句点。这更加一致,让我相信 测试支柱 由于某种原因不被视为实例属性。

    为什么会这样?要将此属性视为实例属性,需要对类做什么?

    3 回复  |  直到 12 年前
        1
  •  12
  •   sharptooth    12 年前

    添加 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
                {
                }
            }
        }
    }
    
        2
  •  1
  •   bruno conde    17 年前

    尝试添加以下标记:

    System.Reflection.BindingFlags.Instance
    

    编辑: 这是可行的(至少对我来说)

    PropertyInfo test = typeof(TestClass).GetProperty("TestProp", BindingFlags.Public | BindingFlags.Instance);
    
    Console.WriteLine(test.Name);
    
        3
  •  0
  •   leppie    17 年前

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