【问题标题】:Get the property name as string in C# [duplicate]在C#中将属性名称作为字符串获取[重复]
【发布时间】:2023-03-13 00:37:01
【问题描述】:

是否可以编写一个返回对象属性的字符串值的函数?

如果我有一个名为 apple 的对象,该对象有一个名为 deep 的方法,我希望有一个在调用 getAttributeName(apple.peel) 时返回“peel”的方法。

我该怎么做?

【问题讨论】:

标签: c# reflection


【解决方案1】:

你可以写一个扩展方法

public static string GetPropName<T, P>(this T obj, Expression<Func<T, P>> lambda)
{
    var member = lambda.Body as MemberExpression;
    var prop = member.Member as PropertyInfo;
    return prop.Name;
}

并像这样使用它

var u = new User();
string name = u.GetPropName(x=>x.name);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 2014-03-01
    • 2020-12-03
    • 1970-01-01
    • 2012-05-04
    相关资源
    最近更新 更多