Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MethodBuilder不支持GetILGenerator方法_C#_Reflection - Fatal编程技术网

C# MethodBuilder不支持GetILGenerator方法

C# MethodBuilder不支持GetILGenerator方法,c#,reflection,C#,Reflection,我试图通过反射API生成泛型方法。下面是我要创建的函数: public List<T> CreateList<T>() { return new List<T>(); } 但在执行过程中,create_list_method.GetILGenerator在处接收到NotSupportedException,并显示以下消息: 其他信息:不支持指定的方法 这种方法有什么问题?我签出了文档,看起来还可以。收到的异常是: [System.NotSupport

我试图通过反射API生成泛型方法。下面是我要创建的函数:

public List<T> CreateList<T>()
{
    return new List<T>();
}
但在执行过程中,create_list_method.GetILGenerator在处接收到NotSupportedException,并显示以下消息:

其他信息:不支持指定的方法


这种方法有什么问题?我签出了文档,看起来还可以。

收到的异常是:

[System.NotSupportedException:不支持指定的方法。] 位于System.Reflection.Emit.TypeBuilderInstantiation.GetConstructorsBindingFlags bindingAttr 在GenericMethodBuilder.Main:第26行

在GetConstructor调用时

发生这种情况是因为您试图获取尚未可构造类型列表的构造函数

方法是使用static TypeBuilder.GetConstructor-method的魔力来创建泛型类型构造函数的适当表示:

ilgen.EmitOpCodes.Newobj,TypeBuilder.GetConstructort_list_type,typeofList.GetConstructors[0]


的msdn条目提供了相当广泛的解释和示例。

哦,谢谢,它解决了我的问题
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

class GenericMethodBuilder
{
    public static void Main()
    {
        var asmName = new AssemblyName("DemoMethodBuilder1");
        var demoAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);

        var demoModule = demoAssembly.DefineDynamicModule(asmName.Name, asmName.Name + ".dll");
        var demoType = demoModule.DefineType("DemoType", TypeAttributes.Public);

        var create_list_method = demoType.DefineMethod("CreateList", MethodAttributes.Public | MethodAttributes.Static);

        var TInput = create_list_method.DefineGenericParameters(new string[] { "TInput" })[0];
        var t_list_type = typeof(List<>).MakeGenericType(TInput);

        create_list_method.SetParameters(Type.EmptyTypes);
        create_list_method.SetReturnType(t_list_type);

        var ilgen = create_list_method.GetILGenerator();

        ilgen.Emit(OpCodes.Newobj, t_list_type.GetConstructors()[0]);
        ilgen.Emit(OpCodes.Ret);

        Type dt = demoType.CreateType();
        demoAssembly.Save(asmName.Name + ".dll");
    }
}