c# - 为什么 GetProperty 找不到它?

标签 c# reflection properties

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


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/

相关文章:

c# - 抽象属性的可访问性

c# - 在构造函数上调用 MethodBase 的 Invoke(反射)

c# - C#中使用反射获取字段的属性

C# 等效于 C++ 宏并使用 Auto<> 属性

JavaScript:如何修复未正确分配属性值的实例

c# - 无法动态地向页面添加控件

c# - 有没有一种方法可以让 switch 使用 C# 8 switch 表达式返回字符串值?

c# - 从结构数组中删除 double

Java 反射 'NoClassDef' 错误

Java Web 应用程序属性