'Can't use custom extension methods with IronPython

I have some extension methods I defined in my C# class, which I can import just fine into an IronPython script. However, when I attempt to call one of these methods (the "Find" method):

cmd.SetSpending(galaxy.Mod.Technologies.Find("Propulsion"), 100);

I get an error: "expected Predicate[Technology], found str".

I don't understand what's wrong - the extension method takes as its first parameter (the "this" parameter) an IEnumerable, which is what galaxy.Mod.Technologies is, and as its second a string, which is what I'm passing in. I'm importing it like so:

import FrEee;
import FrEee.Utility;
clr.ImportExtensions(FrEee.Utility.Extensions);

where FrEee.Utility.Extensions is a namespace containing CommonExtensions.cs, in which the Find method is defined.

I can call the "stock" System.Linq extension methods such as Single just fine:

techs = galaxy.Mod.Technologies;
tech = techs.Single(lambda t: t.Name == "Propulsion");

This accomplishes the exact same thing as my Find method, but I really would like to be able to use custom extension methods. Are they simply not supported in IronPython, or are only extension methods that take a Predicate supported for some reason?



Solution 1:[1]

It seems you have a name conflict. .Net has it's own .Find() extension method defined. Rename yours to something else (like FindName()) and it should work.

Solution 2:[2]

this works for me

C# lib MyLibrary/Extensions.cs

using A = ExternalLib.ClassA;

namespace MyLibrary {

public static class Extensions {

  public static string Id(this A a) {
    return 1;
  }

}

}

IronPython code

import clr
clr.AddReferenceToFileAndPath("C:\\path\\to\\MyLibrary.dll")
from MyLibrary import Extensions as mle

a = A() # classA from somewhere ...
print("get Id %d" % mle.Id(a))

returns 1, as expected.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adam Schmalhofer
Solution 2 angelo.mastro