【问题标题】:Why does GetProperty fail to find it?为什么 GetProperty 找不到它?
【发布时间】: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


    【解决方案1】:

    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
                {
                }
            }
        }
    }
    

    【讨论】:

    • 如果我这样做,GetProperties 也不会返回任何内容,这至少是一致的。但问题是:我需要做什么才能使用 GetProperty 找到该属性?为什么 TestProp 不被视为 Instance 属性?
    • ...或者我需要对 TestClass 进行什么分类才能使其属性显示为实例属性?
    • 我无法复制您的问题(虽然我使用的是 VS2005,所以我必须通过实现来充实您的属性)。
    • 我也不能。我复制了您的示例,删除了属性实现,一切正常。将我原来的示例粘贴回去,它也运行良好。尝试了很多事情来弄清楚我做了什么,但没有运气。哦,好的,感谢您抽出宝贵时间。
    • 每个。单身的。时间。 (我忘记了!)
    【解决方案2】:

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

    【讨论】:

    • 查看上面对 Andrew Rolling 帖子的评论。
    【解决方案3】:

    尝试添加以下标签:

    System.Reflection.BindingFlags.Instance
    

    编辑:这行得通(至少对我来说)

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

    【讨论】:

    • 参见上面 Andrew Rolling 的帖子。
    • 你一定是做错了雷米,因为根据你给我们的例子,这很好......
    • 它现在也适合我。我无法解释;责怪用户:-) 谢谢。
    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 2010-10-19
    • 2015-04-03
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2011-06-17
    • 2020-11-18
    相关资源
    最近更新 更多