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!;
}
}
标签:Name,csharp,字符串,new,PropertySupport,expression,public,string,属性
From: https://www.cnblogs.com/zhuoss/p/17999223