有什么方法可以从该属性的 getter 获取 PropertyInfo 吗?

发布于 2024-09-14 11:58:35 字数 272 浏览 4 评论 0原文

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

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

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

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

Is there any way I can get the PropertyInfo for a property from its getter? Like this:

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

I want to avoid having to hard code the name of the property as a string, as that's tricky to maintain.

I'm using .NET 2.0, so I'm hoping for a linq-less solution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

四叶草在未来唯美盛开 2024-09-21 11:58:35

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

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

MethodBase.GetCurrentMethod() will return the MethodInfo object for get_YourPropertyName.

PropertyInfo property = GetType()
                            .GetProperty(MethodBase
                                             .GetCurrentMethod()
                                             .Name
                                             .Substring("get_".Length)
                                        );
日暮斜阳 2024-09-21 11:58:35

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

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

的方法来完成,尽管它需要 lambda & 。表达式<> (这两者在 C# v2 中都不可用)

Um... So how were you planning on being "given" the getter?

The only way I see is by something like MyGetProperyInfo(x => x.Foo);

which can be done, although it requires a lambda & an Expression<> (neither of which is available in C# v2)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文