如何避免使用字符串成员的名字来获得一个匿名类型的成员? [英] How can I avoid using a string member name to get a member of an anonymous type?
问题描述
我用下面的code检索匿名类型命名的成员。有没有一些方法,我可以转换follwing code使用lambda EX pression实现这一目标,或者至少允许调用code使用LAMDA,即使内心深处我有使用一个字符串?
私人牛逼GetAnonymousTypeMember< T>(对象anonymousType,串成员名),其中T:类
{
变种anonTypesType = anonymousType.GetType();
VAR propInfo = anonTypesType.GetProperty(成员名);
返回propInfo.GetValue(anonymousType,NULL)为T;
}
增加:
这就是 anonymousType
到达。该 GetAnonymousTypeMember
方法是私有的一类,其唯一的公共方法声明如下:
公共无效PublishNotification(NotificationTriggers触发,对象templateParameters)
我把这种方式:
PublishNotification(NotificationTriggers.RequestCreated,新{NewJobCard =模型});
这是新{NewJobCard =模型}
是什么,是传递给 GetAnonymousTypeMember
为 anonymousType
。
公共üGetMemberValue< T,U>(T例如,前pression< Func键< T,U> >选择器)
{
类型类型= typeof运算(T);
VAR EXPR = selector.Body为MemberEx pression;
字符串名称= expr.Member.Name;
VAR道具= type.GetProperty(名称);
返程(U)prop.GetValue(例如,NULL);
}
将使要做到:
字符串名称= GetMemberValue(新{名称=你好},O => o.Name);
I'm using the following code to retrieve named members from an anonymous type. Is there some way I could convert the follwing code to use a lambda expression to achieve this, or at least to allow the calling code to use a lamda, even if 'deep down' I have to use a string?
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});
That new {NewJobCard = model}
is what is passed to GetAnonymousTypeMember
as anonymousType
.
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);
}
Will enable to to do:
string name = GetMemberValue(new { Name = "Hello" }, o => o.Name);
这篇关于如何避免使用字符串成员的名字来获得一个匿名类型的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!