是否可以将 IronPython 类声明为“导出”,从而将它们添加到主机 C# 应用程序可以导入的 MEF 目录中?
我真的找不到任何具体的例子,只是猜测。
以下是我手动加载实现 .NET 接口的 Python 类的方法:
https://github.com/versionone/VersionOne.SDK.Experimental
我希望能够像在 C# 中那样将属性放在 python 类上。(或等效的东西)
有没有人试过这个?
谢谢,乔什
是否可以将 IronPython 类声明为“导出”,从而将它们添加到主机 C# 应用程序可以导入的 MEF 目录中?
我真的找不到任何具体的例子,只是猜测。
以下是我手动加载实现 .NET 接口的 Python 类的方法:
https://github.com/versionone/VersionOne.SDK.Experimental
我希望能够像在 C# 中那样将属性放在 python 类上。(或等效的东西)
有没有人试过这个?
谢谢,乔什
对于那些感兴趣的人,我在 GitHub 上找到了一个项目,它已经做到了这一点,但有点耦合到项目中。经作者批准,我创建了一个新的存储库IronPythonMef和一个NuGet 包。
在 GitHub 上的这个线程中有额外的讨论。
这是它如何工作的示例:
首先,在 C# 中声明的接口:
namespace IronPythonMef.Tests.Example.Operations
{
public interface IOperation
{
object Execute(params object[] args);
string Name { get; }
string Usage { get; }
}
}
在 C# 中导出该接口的实现:
[Export(typeof(IOperation))]
public class Power : IOperation
{
public object Execute(params object[] args)
{
if (args.Length < 2)
{
throw new ArgumentException(Usage, "args");
}
var x = Convert.ToDouble(args[0]);
var y = Convert.ToDouble(args[1]);
return Math.Pow(x, y);
}
public string Name
{
get { return "pow"; }
}
public string Usage
{
get { return "pow n, y -- calculates n to the y power"; }
}
}
并且,IronPython 中 IOperation 的实现:
@export(IOperation)
class Fibonacci(IOperation):
def Execute(self, n):
n = int(n)
if n == 0:
return 0
elif n == 1:
return 1
else:
return self.Execute(n-1) + self.Execute(n-2)
@property
def Name(self):
return "fib"
@property
def Usage(self):
return "fib n -- calculates the nth Fibonacci number"
下面是一个从 C# 和 IronPython 导入这些操作并执行它们的类的测试用例:
[TestFixture]
public class MathWizardTests
{
[Test]
public void runs_script_with_operations_from_both_csharp_and_python()
{
var mathWiz = new MathWizard();
new CompositionHelper().ComposeWithTypesExportedFromPythonAndCSharp(
mathWiz,
"Operations.Python.py",
typeof(IOperation));
const string mathScript =
@"fib 6
fac 6
abs -99
pow 2 4
";
var results = mathWiz.ExecuteScript(mathScript).ToList();
Assert.AreEqual(8, results[0]);
Assert.AreEqual(720, results[1]);
Assert.AreEqual(99f, results[2]);
Assert.AreEqual(16m, results[3]);
}
}