为什么失败的getProperty找到它? [英] Why does GetProperty fail to find it?

查看:158
本文介绍了为什么失败的getProperty找到它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用反射来得到一个类的属性。下面是一些示例代码,我所看到的:

I'm trying to use reflection to get a property from a class. Here is some sample code of what I'm seeing:


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

当我通过这个跟踪,这是我所看到的:

When I trace through this, this is what I see:


  • 当我用获取的所有属性的GetProperties() ,由此产生的阵列有一个入口,财产 TestProp

  • 当我尝试获取 TestProp 使用的getProperty(),我得空回来。

  • When I fetch all properties using GetProperties(), the resulting array has one entry, for property TestProp.
  • When I try to fetch TestProp using GetProperty(), I get null back.

我有点难倒;我一直没能找到在MSDN对于任何的getProperty()这个结果解释给我听。 ?任何帮助。

I'm a little stumped; I haven't been able to find anything in the MSDN regarding GetProperty() to explain this result to me. Any help?

编辑:

如果我想补充 BindingFlags.Instance 的GetProperties()通话,没有属性被发现,期。这是比较一致的,并导致我相信 TestProp 不考虑由于某种原因实例属性。

If I add BindingFlags.Instance to the GetProperties() call, no properties are found, period. This is more consistent, and leads me to believe that TestProp is not considered an instance property for some reason.

为什么会是这样?什么我需要做的类此属性被认为实例属性?

Why would that be? What do I need to do to the class for this property to be considered an instance property?

推荐答案

添加 BindingFlags.Instance 的getProperty 呼叫

编辑:在回应评论...

In response to comment...

下面的代码返回属性。

请注意:这是一个好主意,实际上使你的属性做一些尝试检索它(VS2005)前:)

Note: It's a good idea to actually make your property do something before you try to retrieve it (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
            {
            }
        }
    }
}

这篇关于为什么失败的getProperty找到它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆