Python for .NET:在多个版本中使用相同的 .NET 程序集

Python for .NET: Using same .NET assembly in multiple versions

我的问题:我有两个版本的程序集,想在我的 Python 项目中同时使用它们。

.NET 库安装在 GAC (MSIL) 中,具有相同的 public 标记:

lib.dll (1.0.0.0)
lib.dll (2.0.0.0)

在 Python 我想要这样的东西:

import clr
clr.AddReference("lib, Version=1.0.0.0, ...")
from lib import Class
myClass1 = Class()
myClass1.Operation()

*magic*

clr.AddReference("lib, Version=2.0.0.0, ...")
from lib import class
myClass2 = Class()
myClass2.Operation()
myClass2.OperationFromVersion2()

*other stuff*

# both objects should be accessibly
myClass1.Operation() 
myClass2.OperationFromVersion2()

有办法吗?与 AppDomains 或 bindingRedirect 有关吗?

注意:当然 myClass1.operationFromVersion2() 可能会失败...

好吧,我找到了一个解决方案:Python for .NET 也支持反射!

而不是

clr.AddReference("lib, Version=1.0.0.0, ...")

你必须使用

assembly1 = clr.AddReference("lib, Version=1.0.0.0, ...")

通过该程序集,您可以像在 C# 中一样使用所有反射功能。在我的示例中,我必须使用以下代码(与版本 2 相同):

from System import Type
type1 = assembly1.GetType(...)
constructor1 = type1.GetConstructor(Type.EmptyTypes)
myClass1 = constructor1.Invoke([])

我无法使用已接受的答案使其正常工作。这是我的解决方案。

您必须直接使用 .NET 框架而不是使用 PythonNet:

import System

dll_ref = System.Reflection.Assembly.LoadFile(fullPath)
print(dll_ref.FullName)
print(dll_ref.Location)

检查是否使用了正确的 DLL。

要使用相同版本的多个 DLL,只需将其加载到另一个变量即可

another_dll_ref = System.Reflection.Assembly.LoadFile(anotherFullPath)

现在您可以使用指定 dll 中的对象了。

public 非静态 class

的实例
some_class_type = dll_ref.GetType('MyNamespace.SomeClass')
my_instance = System.Activator.CreateInstance(some_class_type)
my_instance.a = 4 # setting attribute
my_instance.b('whatever') # calling methods

在 public 静态 class

中调用方法
some_class_type = dll_ref.GetType('MyNamespace.SomeClass')
method = some_class_type.GetMethod('SomeMethod')
# return type and list of parameters
method.Invoke(None, [1, 2.0, '3']) 

正在创建结构实例

some_struct_type = dll_ref.GetType('MyNamespace.SomeStruct')
my_struct = System.Activator.CreateInstance(some_struct_type)
my_struct.a = 3

(摘自我的问题