繁体   English   中英

C# TypeBuilder 动态生成具有函数的类

[英]C# TypeBuilder Generate Class with Function Dynamically

我正在尝试在 C# 中使用 TypeBuilder 来动态生成带有函数的类,并让该函数调用另一个基本函数。

需要这样做的原因是,在 Revit 应用程序开发中,每个按钮都需要有一个类,该类使用 Execute 函数实现 IExternalCommand。 我想动态创建按钮并根据它们的 ID 在运行时处理它们的执行,因此我也需要动态创建类。

希望这段代码能找到我正在寻找的东西(或这里http:\/\/pastebin.com\/eehGKteT<\/a> ):

using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Reflection.Emit;

namespace Centek_Revit_Addin
{
    class DynamicButton
    {
        // I would like to use a function like this to generate the class during runtime, presumably using TypeBuilder:
        public static void generateClass(int id)
        {
            // ... Code which would generate a class with the name "GeneratedClass" with the 'id' parameter appended at the end
            // ... The class implements IExternalCommand
            // ... The class has an Execute function with the parameters listed in the example, which returns a call to the Execute function in DynamicButton
            //      along with the added integer 'id' parameter at the end
        }

        public static Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, ref string message, ElementSet elements, int id)
        {
            TaskDialog.Show("About", "ID of the class that called us: " + id);
            return Autodesk.Revit.UI.Result.Succeeded;
        }
    }


    // ===== This class would have been generated during runtime using generateClass(15) ====== //
    class GeneratedClass15 : Autodesk.Revit.UI.IExternalCommand
    {
        public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData revit, ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            return DynamicButton.Execute(revit, ref message, elements, 15);
        }
    }
    // =================================================================== //
}

首先,您必须修复所使用的参数类型。 请注意, message参数具有ref属性,因此您应该将typeof(String)更改为Type.GetType("System.String&")

在必须声明您的execute方法之后,可以从接口实现(重写)execute方法:

tb.DefineMethodOverride(mbExecute, typeof(IExternalCommand).GetMethod("Execute"));

我使用console应用程序进行了一些测试,并通过上面的更改使它能够正常工作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Reflection.Emit;

namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            int a;
            string s = "";
            while ((a = int.Parse(Console.ReadLine())) != 0)
            {


                var t = DynamicButton.generateClass(a);

                ((IExternalCommand)t.GetConstructor(new Type[0]).Invoke(new object[0])).Execute(null, ref s, null);
            }
        }
    }

    public interface IExternalCommand
    {
        Result Execute(ExternalCommandData revit, ref string message, ElementSet elements);
    }

    public class DynamicButton
    {
        // I would like to use a function like this to generate the class during runtime, presumably using TypeBuilder:
        public static Type generateClass(int id)
        {
            // ... Code which would generate a class with the name "GeneratedClass" with the 'id' parameter appended at the end
            // ... The class implements IExternalCommand
            // ... The class has an Execute function with the parameters listed in the example, which returns a call to the Execute function in DynamicButton
            //      along with the added integer 'id' parameter at the end

            AssemblyName aName = new AssemblyName("DynamicAssemblyExample");
            AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.RunAndSave);

            // For a single-module assembly, the module name is usually 
            // the assembly name plus an extension.
            ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");

            // Create class which extends Object and implements IExternalCommand
            var implements = new Type[] {typeof(IExternalCommand)};
            TypeBuilder tb = mb.DefineType("GeneratedClass" + id, TypeAttributes.Public, typeof(Object), implements);


            // Create 'Execute' function sig
            Type[] paramList = {typeof(ExternalCommandData), Type.GetType("System.String&"), typeof(ElementSet)};
            MethodBuilder mbExecute = tb.DefineMethod("Execute", MethodAttributes.Public | MethodAttributes.Virtual, typeof(Result), paramList);

            // Create 'Execute' function body
            ILGenerator ilGen = mbExecute.GetILGenerator();

            ilGen.Emit(OpCodes.Nop);
            ilGen.Emit(OpCodes.Ldarg_1);
            ilGen.Emit(OpCodes.Ldarg_2);
            ilGen.Emit(OpCodes.Ldarg_3);

            ilGen.Emit(OpCodes.Ldc_I4_S, id);

            Type[] paramListWID = { typeof(ExternalCommandData), Type.GetType("System.String&"), typeof(ElementSet), typeof(int) };
            ilGen.EmitCall(OpCodes.Call, typeof(DynamicButton).GetMethod("Execute"), paramListWID);


            ilGen.Emit(OpCodes.Ret);



            tb.DefineMethodOverride(mbExecute, typeof(IExternalCommand).GetMethod("Execute"));
            return tb.CreateType();
        }

        public static Result Execute(ExternalCommandData revit, ref string message, ElementSet elements, int id)
        {
            Console.WriteLine("About {0}", "ID of the class that called us: " + id);
            return Result.Succeeded;
        }
    }

    public enum Result
    {
        Succeeded
    }

    public class ExternalCommandData { }
    public class ElementSet { }
    // =================================================================== //
}

我知道已经过去了几年,但想知道是否还有其他想法。

我们正在尝试重现此代码以使用在 Revit 中实现的 IExternalCommand 创建动态类,但没有创建任何类,可能是因为 Revit 阻止了它们。 你们有没有人让它在 Revit 中工作?

非常感谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM