【发布时间】:2010-05-06 03:43:19
【问题描述】:
我想使用 PropertyType 返回的类型来创建类型化函数。我发现这个类似 using type returned by Type.GetType() in c# 但这提到了如何创建一个列表,但没有提到我们如何创建一个 Func。请帮帮我。
伪代码:
PropertyInfo inf = typeof(SomeClass).GetProperty("PropertyName");
Type T=inf.PropertyType;
Expression<Func<SomeClass,T>> le = GetPropertyOrFieldByName<SomeClass,T>("PropertyName");
static Expression<Func<TSource, TResult>> GetPropertyOrFieldByName<TSource,TResult>(string propertyOrFieldName)
{
ParameterExpression item = Expression.Parameter(typeof(TSource), "expr");MemberExpression prop = LambdaExpression.PropertyOrField(item, propertyOrFieldName);
var expr = Expression.Lambda<Func<TSource, TResult>>(prop, new ParameterExpression[] { item });
expr.Compile();
return expr;
}
【问题讨论】:
-
你能展示一些你想要实现的伪代码吗?你的问题有点含糊。
-
你想创建委托实例还是什么?
-
对不起,如果有点含糊...这里有一些代码..这是我想做的... PropertyInfo inf = typeof(SomeClass).GetProperty("PropertyName");类型 T=inf.PropertyType;表达式
> le = GetPropertyOrFieldByName ("PropertyName"); -
@vsj 好的,但是你打算以后用它做什么?您将无法正常使用它
-
@Andrey ..好吧,我有这个 GetPropertyOrFieldByName Func 它获取类的那个字段......稍后使用它我得到相应字段的值......所以基本上如果我知道我可以将它传递给该函数的类型...
标签: c# reflection gettype