簡體   English   中英

如何在運行時向我的 class 添加方法?

[英]How can I add a method to my class due run-time?

我正在嘗試制作一個 KI 或更像一個可以學習一點的 Bot 的東西。 例如我想給他新的命令。 因此,機器人必須在運行時創建新的方法,以便它可以使用正確的方法對我的輸入做出反應。 我想知道是否以及如何在運行時將方法添加到我現有的 class 中。

我已經找到了一些鏈接以及CodeDomProviderCSharpCodeProviderDynamicMethod等示例,但它們似乎只能創建新的可運行文件(exe 文件)或創建一個可以使用新參數執行的預設。

我需要的是一種在我現有的 class 中創建新方法的方法,或者一種與我現有的 class 交互的方法。 我已經在考慮插件,但在我看來,為每種方法創建一個插件會做很多工作,而且效率也不高,對嗎?

您可能還知道為每個命令創建方法更好的方法?

編輯1:

使用Assembly.CreateInstane("path"); 我可以“克隆”我正在運行的程序,並與 CSharpCodeProvider 一起使用這些方法創建一個新的 exe。 但有一個問題。 當我使用 Class 中沒有引用的方法時,例如using System.Windows.Forms給我錯誤:

第 3 行,錯誤號:CS0234,命名空間“系統”中不存在“類型或命名空間名稱“Windows”。 (是否缺少程序集引用?);

那將是我現在的測試代碼:

//The String I am going to Add through my textfield
using System;
using System.Reflection;
using System.Windows.Forms;

public class Example
{
   public static void Main()
   {
      Assembly assem = typeof(View).Assembly;
      View v = (View ) assem.CreateInstance("Usopis");
      if (! (v == null)) {
         v.Height = 300;
         MessageBox.Show("Instantiated a {0} object whose value is '{1}'",
                           v.GetType().Name, v);
      }
      else {
         MessageBox.Show("Unable to instantiate a View object.");
      }   
   }
}
//Code which should compile my String to a exe

private void Button_Click(object sender, EventArgs e) {
    textBox2.Text = "";
    CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
    CompilerParameters parameters = new CompilerParameters();
    parameters.GenerateExecutable = true;
    CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, textBox1.Text);

    if(results.Errors.Count > 0) {
        textBox2.ForeColor = Color.Red;
        foreach(CompilerError CompErr in results.Errors) {
            textBox2.Text = textBox2.Text +
                        "Line number " + CompErr.Line +
                        ", Error Number: " + CompErr.ErrorNumber +
                        ", '" + CompErr.ErrorText + ";" +
                        Environment.NewLine + Environment.NewLine;
        }
    } else {
        //Successful Compile
        textBox2.ForeColor = Color.Blue;
        textBox2.Text = "Success!";
    }
}

要修復缺少的命名空間錯誤,您必須添加缺少的引用:

parameters.ReferencedAssemblies.Add("System.Web.dll");

但這並不能解決你所有的問題。
也許看看拉姆達斯......
這可能適合你:
https://www.strathweb.com/2018/01/easy-way-to-create-ac-lambda-expression-from-a-string-with-roslyn/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM