簡體   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