1 public class TypeInfoHelper 2 { 3 public static string GetPropertyName<T>(Expression<Func<T, dynamic>> property) 4 { 5 var propertyName = string.Empty; 6 var body = property.Body; 7 if (body.NodeType == ExpressionType.Convert) 8 { 9 var o = (body as UnaryExpression).Operand; 10 propertyName = ((o as MemberExpression).Member as PropertyInfo).Name; 11 } 12 else if (body.NodeType == ExpressionType.MemberAccess) 13 { 14 propertyName = ((body as MemberExpression).Member as PropertyInfo).Name; 15 } 16 return propertyName; 17 } 18 }
先定义个实体用来测试:
1 public class Product 2 { 3 public int Id { get; set; } 4 public string Name { get; set; } 5 public string Description { get; set; } 6 }
使用:
1 var feildName = TypeInfoHelper.GetPropertyName<Product>(s => s.Description); 2 Console.WriteLine(feildName);
时间: 2024-11-03 22:04:41