Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multi parameter delegation #47

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/NReco.LambdaParser.Tests/LambdaParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,32 @@ public void EvalCachePerf() {
Console.WriteLine("10000 iterations: {0}", sw.Elapsed);
}

[Fact]
public void MultiParameterFunc()
{
var lambdaParser = new LambdaParser(new OptionsParamsInvokeMethod());

var context = getContext();
context["f"] = new Funcs();
context["sum"] = new Func<object, decimal>((p) =>
{
if (p is ICollection collection)
{
return collection.Cast<object>().Select(w =>
{
decimal.TryParse(w?.ToString(), out var value);
return value;
})?.Sum() ?? 0;
}

decimal.TryParse(p?.ToString(), out var value1);
return value1;
});

Assert.Equal(13M,
lambdaParser.Eval("sum(1,2,3) + sum(1) + f.sum(1,2,3)", context));
}


public class TestBaseClass
{
Expand Down Expand Up @@ -295,5 +321,24 @@ public string Format(string format,params object[] args)

}


public class Funcs
{
public decimal sum(params object[] p)
{
if (p is ICollection collection)
{
return collection.Cast<object?>().Select(w =>
{
decimal.TryParse(w?.ToString(), out var value);
return value;
})?.Sum() ?? 0;
}

return 0;
}
}


}
}
13 changes: 13 additions & 0 deletions src/NReco.LambdaParser/Linq/LambdaParameterWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,19 @@ public LambdaParameterWrapper InvokeDelegate(object obj, object[] args) {
var deleg = (Delegate)obj;

var delegParams = deleg.GetMethodInfo().GetParameters();

// If it is a parameter and the parameter type is object (如果是一个参数 并且 参数类型是 object)
var isParams = delegParams.Length == 1 &&
delegParams[0].ParameterType == typeof(object) &&
delegParams.Length != args.Length;
if (isParams)
{
var resolvedArgList = args
.Select(w => w is LambdaParameterWrapper ? ((LambdaParameterWrapper)w).Value : w)
.ToArray();
return new LambdaParameterWrapper(deleg.DynamicInvoke((object)resolvedArgList), Ctx);
}

if (delegParams.Length != args.Length)
throw new TargetParameterCountException(
String.Format("Target delegate expects {0} parameters", delegParams.Length));
Expand Down