欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 获取属性名的方法

程序员文章站 2023-11-29 13:57:40
复制代码 代码如下:using system;using system.collections.generic;using system.linq;using system...

复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.linq.expressions;
using system.text;
using system.threading.tasks;
namespace consoleapplication
{
    class program
    {
        class test
        {
            public string propertyjustfortest1 { get; set; }
            public test propertyjustfortest2 { get; set; }
        }
        static void main(string[] args)
        {
            test test = new test();
            console.writeline(getpropertynamehelper.getpropertyname<object>(() => test.propertyjustfortest1));
            console.writeline(getpropertynamehelper.getpropertyname<object>(() => test.propertyjustfortest2));
        }
    }
    static class getpropertynamehelper
    {
        public static string getpropertyname<t>(expression<func<t>> express)
        {
            var memberexpress = express.body as memberexpression;
            if (memberexpress != null)
            {
                return memberexpress.member.name;
            }
            else
            {
                return string.empty;
            }
        }
    }
}