How can I avoid using a member name of a string to get a member of an anonymous type?

I use the following code to extract named members from an anonymous type. Is there a way to convert the follwing code to use a lambda expression to achieve this, or at least allow the calling code to use lamda, even if I need to use the string "deep down"?

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

ADDED: This is how anonymousType arrives. The GetAnonymousTypeMember method is private to a class whose only public method is declared as follows:

public void PublishNotification (NotificationTriggers trigger, object templateParameters)

I call this method:

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

This new {NewJobCard = model} is what GetAnonymousTypeMember is GetAnonymousTypeMember as anonymousType .

+4
source share
4 answers
 public U GetMemberValue<T, U>(T instance, Expression<Func<T, U>> 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); } 

Allows you to do:

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

But why don't you just use the dynamics? eg:

 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(); } } 

You can also enable ExpandoObject

 List<dynamic> objs = new List<dynamic>(); 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(); 
+1
source

No, when you send an object as an object type, there is no specific type information for the parameter. If you want to access the elements of an object, you need to use reflection to get type information from the object itself.

Using a lambda expression to get a member would work, but that would be completely pointless ...

0
source

Do you mean something like this?

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

All Articles