microsoft / ClearScript

A library for adding scripting to .NET applications. Supports V8 (Windows, Linux, macOS) and JScript/VBScript (Windows).
https://microsoft.github.io/ClearScript/
MIT License
1.74k stars 148 forks source link

The best overloaded method match for 'System.Collections.Generic.List<Brick>.Find(System.Predicate<Brick>)' has some invalid arguments #472

Closed MixaMega closed 1 year ago

MixaMega commented 1 year ago

I have a static class called Game, in it theres a property called Bricks which is a List

engine.AddHostType("Console", typeof(Console));
engine.AddHostType("Game", typeof(Game));

engine.Execute(@"Game.Bricks.Find((brick) => {brick.Name == 'bob'})");

this code gives me the following error --- Script error details follow --- Error: The best overloaded method match for 'System.Collections.Generic.List<Brick>.Find(System.Predicate<Brick>)' has some invalid arguments at Script:1:13 -> Game.Bricks.Find((brick) => {brick.Name == 'bob'});

ClearScriptLib commented 1 year ago

Hi @MixaMega,

ClearScript can't implicitly convert a JavaScript function to a strongly typed .NET delegate.

However, you have several options. For example, you could perform the conversion explicitly:

engine.AddHostType("BrickPredicate", typeof(Predicate<Brick>));
engine.Execute("Game.Bricks.Find(new BrickPredicate(brick => brick.Name == 'bob'))");

A better option might be to provide a version of Find that works directly with script functions:

public static class ListExtensions {
    public static T Find<T>(this List<T> list, dynamic predicate) {
        return list.Find(item => predicate(item));
    }
}

And then:

engine.AddHostType(typeof(ListExtensions));
engine.Execute("Game.Bricks.Find(brick => brick.Name == 'bob')");

Good luck!

MixaMega commented 1 year ago

Thank you it works!