c# - 怎样在get/set中获取属性名称?

查看:589
本文介绍了c# - 怎样在get/set中获取属性名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

使用MethodBase.GetCurrentMethod().Name方法可以获取当前方法名称,但是用在属性的get/set中的话,得到的名字会有个前缀,还有其它好办法吗?

解决方案

public class Test
{
    private string _name;

    public string Name
    {
        get
        {
            MethodBase method = MethodBase.GetCurrentMethod();
            // GetProperties时可能需要根据实际情况决定需要获取哪些类型的属性
            var property = (from f in method.DeclaringType.GetProperties()
                            where f.GetMethod == method || f.SetMethod == method
                            select f).FirstOrDefault();
            if (property != null)
            {
                Console.WriteLine("当前属性名为:" + property.Name);
            }
            return _name;
        }
        set
        {
            _name = value;
        }
    }
}

这篇关于c# - 怎样在get/set中获取属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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