我正在尝试根据满足特定的标准来序列化一些东西。
为此,我最初的希望是在对象的属性上使用包含lambda表达式的属性。
然而,由于无法做到这一点,我决定在类中拥有一个Func成员,并通过property属性传递此Func的类型(或第一个参数类型)和名称。例如:
Func<SomeObject, bool> func = (p => p.Value == 4);
[FuncAtt(typeof(SomeObject), "func")]
public SomeObject PropertyName { get; set;}在我的序列化程序中,我需要调用这个Func。
假设我有一个类型t,它等于本例中的typeof(SomeObject),或者更抽象地说,typeof(T)。我也可以获取Func本身,但只能通过反射作为对象。
我的天真方法是这样的:
object func = typeof(MyClass).GetField(attribute.FuncName).GetValue(MyClassInstance);
Type funcType = typeof(Func<,>).MakeGenericType(attribute.Type, typeof(bool));
ParameterExpression p = Expression.Parameter(attribute.Type, objectToSerialize);
LambdaExpression l = Expression.Lambda(funcType, func, p); /* Won't work */但这导致了将lambda转换为委托的问题,这显然是错误的。
我试着用这个代替'func':
(Expression)((Action)(() => func))但这依赖于func是一个方法调用,而不是lambda。
那么,谁能给我指个正确的方向?
发布于 2009-09-14 07:42:40
你可以这样做,不需要表达式:
public static class Test
{
public static Predicate<int> func = s => s > 20;
}并获取该值:
private void Form1_Load(object sender, EventArgs e)
{
var a = typeof(Test).GetField("func");
bool validates = ((Predicate<int>)a.GetValue(null)).Invoke(100);
}在不知道类型的情况下编辑以获取值:
bool validates = (bool)((Delegate)a.GetValue(null)).DynamicInvoke(100);发布于 2009-09-14 04:18:16
我认为您可以使用lambda表达式的Compile方法将其转换为委托。
这是我在MSDN上找到的:
Expression<(Of <(TDelegate>)>)类型提供了
方法,该方法将表达式树表示的代码编译为可执行委托。此可执行代码等同于最初将lambda表达式分配给委托类型时生成的可执行代码。
Here你可以找到它。
发布于 2009-09-14 08:38:16
我不确定这是工作样本,但这是正确的方式:
// not sure what are you doing in this line, but assume it should return
// a method name specified in the attribute, e.g. "func" in your example.
// Also "func" must be a method (static one in my example) of SomeObject class
String funcname = typeof(MyClass).GetField(attribute.FuncName).GetValue(MyClassInstance);
ParameterExpression param = Expression.Parameter(typeof(SomeObject), "p");
MethodCallExpression call = Expression.Call(SomeObject, funcname, new Type[] { typeof(SomeObject), typeof(Boolean) }, param);
LambdaExpression lambda = Expression.Lambda<Func<SomeObject, Boolean>>(call, param);现在你可以像这样调用"func“方法:
Boolean result = lambda.Compile()(SomeObjectInstance);https://stackoverflow.com/questions/1419630
复制相似问题