怪奇物语

怪奇物语

首页 新随笔 联系 管理

PropertySupport\Person.cs

public class Person
{
    public string Name { get; set; }

    public string getPropertyName()
    {
        return PropertySupport.ExtractPropertyName(() => Name);
    }
}

PropertySupport\Program.cs

Person person = new Person();
string propertyName = PropertySupport.ExtractPropertyName(() => person.Name);

Console.WriteLine(propertyName);  // 输出 "Name"

Console.WriteLine(person.getPropertyName()); // 输出 "Name"





PropertySupport\PropertySupport.cs

using System.Linq.Expressions;

public static class PropertySupport
{

    public static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression)
    {
        if (propertyExpression == null)
            throw new ArgumentNullException(propertyExpression?.Name);

        return ExtractPropertyNameFromLambda(propertyExpression);
    }


    internal static string ExtractPropertyNameFromLambda(LambdaExpression expression)
    {
        if (expression == null)
            throw new ArgumentNullException(expression?.Name);

        var memberExpression = expression.Body as MemberExpression;

        // if (memberExpression == null)
        // throw new ArgumentException(Resources.PropertySupport_NotMemberAccessExpression_Exception, expression.Name);

        // var property = memberExpression.Member as PropertyInfo;
        // if (property == null)
        // throw new ArgumentException(Resources.PropertySupport_ExpressionNotProperty_Exception, expression.Name);

        // var getMethod = property.GetMethod;
        // if (getMethod.IsStatic)
        // throw new ArgumentException(Resources.PropertySupport_StaticExpression_Exception, expression.Name);

        return memberExpression?.Member.Name!;
    }
}
posted on 2024-01-31 14:39  超级无敌美少男战士  阅读(27)  评论(0)    收藏  举报