0

ユーザーが作成した C# コードを実行するには、Winform アプリケーションでいくつかのコードを動的にコンパイルする必要があります。

いくつかのテストを行うために、私はこの関数を書きました:

public object executeDynamicCode(string code)
        {
            using (Microsoft.CSharp.CSharpCodeProvider foo = new Microsoft.CSharp.CSharpCodeProvider())
            {
                try
                {
                    var res = foo.CompileAssemblyFromSource(
                        new System.CodeDom.Compiler.CompilerParameters()
                        {
                            GenerateInMemory = true
                        },
                        "using System.Windows.Forms; public class FooClass { public void Execute() {MessageBox.Show();}}");
                    if (res.Errors.Count > 0)
                        MessageBox.Show(res.Errors[0].ErrorText);
                    var type = res.CompiledAssembly.GetType("FooClass");
                    var obj = Activator.CreateInstance(type);
                    var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
                    return output;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    return null;
                }
            }
        }

しかし、実行すると、次のエラーが発生しました。

タイプまたは名前空間 Windows が System 名前空間に存在しません (アセンブリ参照がありませんか?)

誰かが何か考えを持っていたら?

前もって感謝します !

4

1 に答える 1