个人资料

跳过导航链接首页 > 博客列表 > 博客正文

C#在属性的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;
        }
    }
}

songshizhao
最初发表2018/9/8 22:06:40 最近更新2018/9/8 22:06:40 4057
为此篇作品打分
10