c# - 如何在 IronPython 中调用 C#/.NET 命名空间?

标签 c# namespaces ironpython

我希望在 IronPython 中复制以下内容,但迄今为止搜索没有结果和/或令人失望。

namespace Groceries
{
     public class ChocolateMilk : Milk
     {
          // Other stuff here
     }
}

这个想法是编译后的 Python DLL 将通过 System.Reflection.Assembly.Load 加载到 C# 程序中,并且加载的 DLL 上的 GetType("Groceries.ChocolateMilk") 不会返回 null。

我能找到的最新答案是在 2008 年,它说不使用托管 API 是不可能的 - http://lists.ironpython.com/pipermail/users-ironpython.com/2008-October/008684.html .

如有任何关于如何实现此目的的建议,我们将不胜感激。任何目前无法通过 IronPython 完成的结论也将受到赞赏,但不那么重要。

最佳答案

我对你在这里问的问题有点困惑。您是否尝试在 IronPython 模块中实例化该 C# 代码?或者您是否有用 IronPython 编写的等效类并且您想在 C# 代码中实例化它们?

根据您发布的链接,我想您会选择后者,并拥有要在 C# 代码中实例化的 IronPython 类。答案是,你不能直接实例化它们。当您将 IronPython 代码编译为程序集时,您不能将在那里定义的类型与您的常规 .NET 代码一起使用,因为 IronPython 类和 .NET 类之间没有一对一的映射。您必须在 C# 项目中托管程序集并以这种方式实例化它。

考虑这个模块,Groceries.py 编译为驻留在工作目录中的 Groceries.dll:

class Milk(object):
    def __repr__(self):
        return 'Milk()'

class ChocolateMilk(Milk):
    def __repr__(self):
        return 'ChocolateMilk()'

在您的 C# 代码中托管模块:

using System;

using IronPython.Hosting;
using System.IO;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        var engine = Python.CreateEngine();
        var groceriesPath = Path.GetFullPath(@"Groceries.dll");
        var groceriesAsm = Assembly.LoadFile(groceriesPath);
        engine.Runtime.LoadAssembly(groceriesAsm);

        dynamic groceries = engine.ImportModule("Groceries");
        dynamic milk = groceries.ChocolateMilk();
        Console.WriteLine(milk.__repr__()); // "ChocolateMilk()"
    }
}

否则走另一条路,在 IronPython 代码中创建 .NET 类型的实例(如您的标题所示)。您需要将路径添加到您的程序集,引用它,然后您可以根据需要实例化它。

# add to path
import sys
sys.path.append(r'C:\path\to\assembly\dir')

# reference the assembly
import clr
clr.AddReferenceToFile(r'Groceries.dll')

from Groceries import *
chocolate = ChocolateMilk()
print(chocolate)

关于c# - 如何在 IronPython 中调用 C#/.NET 命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7719397/

相关文章:

c# - 命名空间 'Window' 中不存在类型或命名空间名称 'System.Windows'

c# - 如何在内部使用 IronPython 引用自包含的 C# 类库项目 (Visual Studio 2010)

python - 从 Python 代码构建 .NET DLL?

c# - C#—在Convert.ToInt32(...)之后,循环将不接受非数字输入

c# - 如何在 ASP.NET MVC 中对私有(private) Controller 方法进行单元测试?

ubuntu - 使用用户命名空间时无法访问 Docker 镜像

visual-studio - VS 2012 中的 Microsoft.VisualStudio.Package

c# - 在 C# 中替换正则表达式字符串

c# - 我如何在 Ninject 中使用装饰器声明责任链?

python - Spotfire 自动导出