小编Dev*_*per的帖子

使用 pythonnet 从 python 调用 C# 代码

以下是 C# 代码。如何使用 pythonnet 从 Python 调用 NonGenericClass 内的 GenericMethod()?

namespace CSharpTestCode
{
    public interface Person
    {
    }

    public class Employee : Person
    {
    }

    public class TempGenericClass<T>
    {
    }

    public class NonGenericClass
    {
        public static T GenericMethod<T>(TempGenericClass<T> tempGeneric) where T : class, Person
        {
            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试过的 Python 代码:

import clr
clr.AddReference(r'\Documents\visual studio 2015\Projects\SamplePythonApp\CSharpTestCode\bin\Debug\CSharpTestCode.dll')
from CSharpTestCode import *

genericMethod = NonGenericClass.GenericMethod(TempGenericClass[Employee]())
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

Unhandled Exception: System.ArgumentException: GenericArguments[0], 'CSharpTestCode.TempGenericClass`1[CSharpTestCode.Employee]', on 'T GenericMethod[T](CSharpTestCode.TempGenericClass`1[T])' violates the constraint of type 'T'. …
Run Code Online (Sandbox Code Playgroud)

c# python interop python.net

5
推荐指数
1
解决办法
2311
查看次数

标签 统计

c# ×1

interop ×1

python ×1

python.net ×1