【问题标题】:Accessing WinForm Controls using C# dynamic code使用 C# 动态代码访问 WinForm 控件
【发布时间】:2015-03-30 02:07:38
【问题描述】:

我有一个名为 Form1 的 WinForm,还有名为 TextBox1TextBox2 的 Button1、MemoEdit1 和 2 个 TextBox。在运行时,用户应该能够在 MemoEdit1 中编写 C# 代码以操作 TextBox 控件。 F.e:在运行时用户输入 MemoEdit1 简单代码,如:TextBox2.Text = "Hello" + TextBox1.Text;

所以,当我点击Button1时,我需要编译并执行代码。

问题听起来很简单,因为我是 C# 运行时编译/执行代码的新手。

您能帮忙吗?

谢谢。

【问题讨论】:

  • “动态代码”是什么意思,为什么要标记这个问题codedom
  • 是的,你写的那行是可能的,为什么不试试而不是问?
  • 我认为问题中缺少一些东西;但现在你问的是可能的。
  • 我知道我必须使用 CodeDom 来编译用户提供的(这就是我称之为动态的)代码,但我不知道如何引用 Form1 控件(在本例中为 TextBox1 和 TextBox2) .谢谢。
  • 您的问题中仍然没有任何内容实际上涉及编译用户提供的代码。看来您的问题仅涉及如何将字符串常量与字符串变量连接起来-如果这是您的问题,我建议您花一些时间查找一些初学者 C# 书籍并阅读。否则,您需要修改您的问题以更好地说明您的要求 - 帮助我们帮助您。

标签: c# .net winforms dynamic codedom


【解决方案1】:

看看这个sn-p

public class Evaluator
{
    public void Eval(string Code)
    {
        Microsoft.CSharp.CSharpCodeProvider Provider = new Microsoft.CSharp.CSharpCodeProvider(); // Create an provider

        System.CodeDom.Compiler.ICodeCompiler Compiler = Provider.CreateCompiler(); // Create An Compiler

        System.CodeDom.Compiler.CompilerParameters Parameters = new System.CodeDom.Compiler.CompilerParameters(); // Create a parameters of the compiler

        Parameters.GenerateInMemory = true; // It should generate the compiled assembly in the memory

        System.CodeDom.Compiler.CompilerResults Results = Compiler.CompileAssemblyFromSource(Parameters, Code); //Compile it

        ///Now you just need to use reflection to call its methods
        object SomeClass = Results.CompiledAssembly.CreateInstance("ClassName"); //Name of the class you want to create an instance
        var Method = SomeClass.GetType().GetMethod("MethodName"); //Name of the Method you want to call
        Method.Invoke(SomeClass, null); // change null for the argument it needs
    }
}

如果您只想编写代码,则必须添加一个类和一个方法来包装用户代码,然后通过 Invoke 调用它,您可能必须将自己的程序集引用到此程序集中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-12
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多