我有一些在运行时编译的代码。今天它使用的是methodinfo。invoke。为了加快速度,我试图创建一个委托/函数,但我似乎找不到正确的重载/参数来实现它。
当前代码在lambda编译上失败,'为lambda声明提供的参数数量不正确'
。净v4.61
如有任何帮助,不胜感激。
// Contrived example code
public class MyItemClass
{
public bool IsDivisableBy3 { get; set; }
public bool IsEven { get; set; }
public MyItemClass(int value)
{
this.IsEven = value % 2 == 0;
this.IsDivisableBy3 = value % 3 == 0;
}
}
public class RuleTestResult
{
public int RuleNumber { get; set; }
public bool Result { get; set; }
}
private static var VbCode = @"Public NotInheritable Class RuleTest
Private Shared Function Rule1(item As MyItemClass) As Boolean
If item.IsEven Then
Return True
End If
End Function
Private Shared Function Rule2(item As MyItemClass) As Boolean
If item.IsEven = False Then
If item.IsDivisableBy3 Then
Return True
End If
End If
End Function
Public Shared Function FindRule(item As MyItemClass) As RuleTestResult
Select Case True
Case Rule1(item)
Return New RuleTestResult With {.RuleNumber = 1, .Result = True}
Case Rule2(item)
Return New RuleTestResult With {.RuleNumber = 2, .Result = True}
Case Else
Return New RuleTestResult With {.RuleNumber = -1, .Result = False}
End Select
End Function
End Class";
public static void TestMe()
{
// Make some test items
var Items = new List<MyItemClass>();
for (var i = 1; i <= 10; i++)
Items.Add(new MyItemClass(i));
// Compile the code
var CompilerResult = Compile(VbCode);
var Instance = CompilerResult.CompiledAssembly.CreateInstance("RuleTest");
var AssType = Instance.GetType();
var Method = Instance.GetType.GetMethod("FindRule");
var Param = Expressions.Expression.Parameter(Method.GetParameters.First.GetType);
// Create a func
Expressions.Expression CallExpression = Expressions.Expression.Call(Method, Param);
var MyFunc = Expressions.Expression.Lambda<Func<MyItemClass,RuleTestResult>>(CallExpression).Compile();
//'Incorrect number of parameters supplied for lambda declaration'
var Results = new List<RuleTestResult>();
foreach (var item in Items)
{
Results.Add(MyFunc(item))
}
}
我想我只是需要发布这个来弄清楚:)
var Param = Expressions.Expression.Parameter(typeof(RuleTest), "item");var MyFunc = Expressions.Expression.Lambda