CLR extension methods #1067
-
Saw a question on Stack Overflow while researching and couldn't get it to work with the extension methods provided by C# itself. // Works
public class Foo
{
public string Name { get; } = "Bar";
}
public static class CustomStringExtensions
{
public static bool StartsWith(this string value, string value2) => value.StartsWith(value2);
}
Engine engine = new Engine(options =>
{
options.AddExtensionMethods(typeof(CustomStringExtensions));
});
bool result = engine
.SetValue("foo", new Foo())
.Evaluate("foo.Name.StartsWith('B')")
.AsBoolean(); // Doesn't work
public class Foo
{
public string Name { get; } = "Bar";
}
Engine engine = new Engine(options =>
{
// Also tried these
//options.AllowClr();
//options.AllowOperatorOverloading();
//options.AddExtensionMethods(typeof(String));
options.AddExtensionMethods(typeof(string));
});
bool result = engine
.SetValue("foo", new Foo())
.Evaluate("foo.Name.StartsWith('B')")
.AsBoolean();
bool result = engine
.SetValue("foo", new Foo())
.Evaluate("foo.Name.StartsWith('B')")
.AsBoolean(); Is it because some overloading? I'm curious about the reason. I see there isn't really anything documented about how the extension method support is to be used. Could an example be added, and maybe also that native extensions methods do not work, or if they do, how they can be added. Thanks! When will version 3 become available, as I see it's already beta since Oct 2016? :) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Your code should work if you write it as Best place to learn about extension methods is to read the related tests I guess. Version 3 is available as beta builds from NuGet, don't know when it hits final stage. |
Beta Was this translation helpful? Give feedback.
-
Thanks! Ahh, sorry, indeed, those aren't extension methods, although they feel like it. |
Beta Was this translation helpful? Give feedback.
options.AddExtensionMethods(typeof(string));
does not make sense asString
doesn't (cannot) contain any extension methods, they reside instatic
classes.Your code should work if you write it as
foo.Name.startsWith('B')
, Jint matches using lower-case first letter by default to follow JS naming. You can override this viaoptions.TypeResolver.MemberNameComparer
configuration.Best place to learn about extension methods is to read the related tests I guess.
Version 3 is available as beta builds from NuGet, don't know when it hits final stage.