日期:2014-05-17 浏览次数:20856 次
public class Model { public int Name { get; set; } } public class GenericModel<T> { public string GetModelPropertyName<TProperty> (Func<T,TProperty> PropertyExpr) { string result = ""; //...这里该如何通过传进来的lambda获取成员名称,即获得result等于Name return result; } } class Program { static void Main(string[] args) { //调用方式 GenericModel<Model> m = new GenericModel<Model>(); Console.WriteLine(m.GetModelPropertyName(g => g.Name)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using System.Diagnostics.Contracts; using System.Reflection; namespace LambdaCallFunc { class Program { static void Main(string[] args) { var test = new GenericModel<Test>(); var pName = test.GetModelPropertyName(g => g.Name); Console.WriteLine(pName); Console.Read(); } } class Test { public string Name { get; set; } } public class GenericModel<T> { public string GetModelPropertyName<TProperty>(Expression<Func<T, TProperty>> propertyExpr) { var path = propertyExpr.GetMemberPathString(); return path; } } public static class ExpressionExtensions { public static String GetMemberPathString<TEntity, TProperty>(this Expression<Func<TEntity, TProperty>> expression) { Contract.Requires(expression != null); Contract.Requires(expression.Body.NodeType == ExpressionType.MemberAccess); MemberExpression body = expression.Body as MemberExpression; LinkedList<string> rval = new LinkedList<string>(); while (body != null) { var propertyName = (body.Member is PropertyInfo) ? body.Member.Name : null; if (!string.IsNullOrEmpty(propertyName)) rval.AddFirst(propertyName); body = body.Expression as MemberExpression; } return String.Join(".", rval); } } }