dynamicexpresso / DynamicExpresso

C# expressions interpreter
http://dynamic-expresso.azurewebsites.net/
MIT License
1.99k stars 374 forks source link

Add support of .net 7.0 #270

Closed zatuliveter closed 1 year ago

zatuliveter commented 1 year ago

I tried to run unit tests on the .net 7.0, everything is working except of linq stuff. The following unit tests are failing:

Error Message:  System.ArgumentException : GenericArguments[1], 'System.Object', on 'TResult Average[TSource,TAccumulator,TResult](System.Collections.Generic.IEnumerable1[TSource])' violates the constraint of type 'TAccumulator'. System.Security.VerificationException : Method System.Linq.Enumerable.Average: type argument 'System.Object' violates the constraint of type parameter 'TAccumulator'.

Linq also fails if you try to use nuget on .net 7.0 project (.net 6.0 are OK).

davideicardi commented 1 year ago

I suspect that the reason is because these packages are not officially intended to be used directly... but I think that in some way we can adapt the code, in the worst case using a conditional compilation. As usual any help is appreciated.

metoule commented 1 year ago

It's actually not related to .NET7, you can reproduce it with this code:

[Test]
public void Method_with_generic_constraints()
{
  var target = new Interpreter();

  var x = new MyTestService();
  target.SetVariable("x", x);

  Assert.AreEqual("works", target.Eval("x.GenericMethodWithConstraint(\"works\")"));
  Assert.Throws<NoApplicableMethodException>(() => target.Eval("x.GenericMethodWithConstraint(5)"), "This shouldn't throw a System.ArgumentException \"Violates the constraint of type 'T'\"");
}

private class MyTestService
{
  public T GenericMethodWithConstraint<T>(T input) where T : class
  {
    return input;
  }
}

You can't call MyTestService.GenericMethodWithConstraint with an integer, as it violates the generic constraints. DynamicExpresso tries to use the method, which triggers a generic constraint violation exception. Instead, it should ignore any generic method if it leads to a constraint violation.