如何避免使用字符串成员名称来获取匿名类型的成员?

我正在使用以下代码从匿名类型中检索命名成员。 有没有什么方法可以转换后续代码使用lambda表达式来实现这一点,或者至少允许调用代码使用lamda,即使“内心深处”我必须使用字符串?

private T GetAnonymousTypeMember(object anonymousType, string memberName) where T: class { var anonTypesType = anonymousType.GetType(); var propInfo = anonTypesType.GetProperty(memberName); return propInfo.GetValue(anonymousType, null) as T; } 

ADDED:这是anonymousType到达的方式。 GetAnonymousTypeMember方法是一个类的私有方法,它的唯一公共方法声明如下:

public void PublishNotification(NotificationTriggers触发器,对象templateParameters)

我称之为这种方法:

 PublishNotification(NotificationTriggers.RequestCreated, new {NewJobCard = model}); 

new {NewJobCard = model}是作为anonymousType传递给GetAnonymousTypeMember

 public U GetMemberValue(T instance, Expression> selector) { Type type = typeof(T); var expr = selector.Body as MemberExpression; string name = expr.Member.Name; var prop = type.GetProperty(name); return (U)prop.GetValue(instance, null); } 

将能够做到:

 string name = GetMemberValue(new { Name = "Hello" }, o => o.Name); 

但是你为什么不用动态? 例如:

 class MyClass { public int member = 123; } class Program { static void Main(string[] args) { MyClass obj = new MyClass(); dynamic dynObj = obj; Console.WriteLine(dynObj.member); Console.ReadKey(); } } 

您还可以参与ExpandoObject

 List objs = new List(); dynamic objA = new ExpandoObject(); objA.member = "marian"; objs.Add(objA); dynamic objB = new ExpandoObject(); objB.member = 123; objs.Add(objB); dynamic objC = new ExpandoObject(); objC.member = Guid.NewGuid(); objs.Add(objC); foreach (dynamic obj in objs) Console.WriteLine(obj.member); Console.ReadKey(); 

你的意思是这样的?

 private R GetAnonymousTypeMember(T anonymousType, Expression> e) where T : class { return e.Compile()(anonymousType); } public void Do() { var x = new {S = "1", V = 2}; var v = GetAnonymousTypeMember(x, _ => _.V); } 

不,当您将对象作为类型object发送时,参数没有特定的类型信息。 如果要访问对象的成员,则需要使用reflection从对象本身获取类型信息。

使用lambda表达式来获取成员会起作用,但这完全没有意义……