获取属性名称在C#中的字符串 [英] Get the property name as string in C#

查看:96
本文介绍了获取属性名称在C#中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to write a function that return the string value of a property of an object?

如果我有一个名为苹果的对象,有一个名为剥离的方法我想有一个返回剥离的方法,当我打电话getAttributeName(apple.peel)。

if I have an object called apple that has a method called peel i would like to have a method that returns "peel" when I call getAttributeName(apple.peel).

我该怎么办呢?

推荐答案

您可以写一个扩展方法

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

这篇关于获取属性名称在C#中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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