3
以下是C#代碼。我如何使用pythonnet從Python中的NonGenericClass內部調用GenericMethod()?使用pythonnet從python調用C#代碼
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;
}
}
}
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]())
錯誤,我得到:
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'. ---> System.Security.VerificationException: Method CSharpTestCode.NonGenericClass.GenericMethod: type argument 'CSharpTestCode.TempGenericClass`1[CSharpTestCode.Employee]' violates the constraint of type parameter 'T'.
at System.RuntimeMethodHandle.GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation)
at System.Reflection.RuntimeMethodInfo.MakeGenericMethod(Type[] methodInstantiation)
--- End of inner exception stack trace ---
at System.RuntimeType.ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
at System.Reflection.RuntimeMethodInfo.MakeGenericMethod(Type[] methodInstantiation)
at Python.Runtime.MethodBinder.MatchParameters(MethodInfo[] mi, Type[] tp)
at Python.Runtime.MethodBinder.Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, MethodInfo[] methodinfo)
at Python.Runtime.MethodBinder.Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, MethodInfo[] methodinfo)
at Python.Runtime.MethodObject.Invoke(IntPtr target, IntPtr args, IntPtr kw, MethodBase info)
at Python.Runtime.MethodBinding.tp_call(IntPtr ob, IntPtr args, IntPtr kw)
你的意思是一個嵌入式IronPython的解釋?否則,你不能直接調用它,你必須以某種方式公開它(許多不同的方式) – UnholySheep
我正在使用pythonnet。我試圖構建這個代碼作爲類庫和python將通過.dll – Developer
訪問此代碼我不知道python語法來調用此方法,因爲它具有方法名稱和方法參數中的泛型類型參數 – Developer