【问题标题】:Is there any way to get the PropertyInfo from the getter of that property?有没有办法从该属性的 getter 中获取 PropertyInfo?
【发布时间】:2011-03-29 20:20:08
【问题描述】:

有什么方法可以从它的 getter 中获取属性的 PropertyInfo 吗?像这样:

public object Foo
{
    get
    {
        PropertyInfo propertyInfoForFoo = xxx;
        ...
    }
}

我想避免将属性名称硬编码为字符串,因为这很难维护。

我正在使用 .NET 2.0,所以我希望有一个无 linq 的解决方案。

【问题讨论】:

标签: c# .net reflection properties propertyinfo


【解决方案1】:

MethodBase.GetCurrentMethod() 将返回 get_YourPropertyName 的 MethodInfo 对象。

PropertyInfo property = GetType()
                            .GetProperty(MethodBase
                                             .GetCurrentMethod()
                                             .Name
                                             .Substring("get_".Length)
                                        );

【讨论】:

    【解决方案2】:

    嗯...那么你打算如何被“给予”吸气剂?

    我看到的唯一方法是MyGetProperyInfo(x => x.Foo);

    可以做到,尽管它需要一个 lambda 和一个表达式(在 C# v2 中都没有)

    【讨论】:

    • Lambda 在 c# 2 中可用,但在 linq 中不可用。不确定表达式.
    • @JOnB: Expression 和所有子类型都在 System.Core 程序集中实现,并在 .NET 3.5 中添加。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    相关资源
    最近更新 更多