2

メイン プロジェクトでコンパイルする以下のようなコードの文字列があるとします。しかし、CustomClass にインターフェースを実装したいと考えています。インターフェースは私のソリューションの別のプロジェクトにあります (私のメインプロジェクトの参照の一部) 私がこれを行うとき

パブリック クラス CustomClass : InterfaceType

このようなエラーが発生します。動的コード内で、他のプロジェクトを参照して、その一部であるインターフェイスや他のクラスを使用できるようにするにはどうすればよいですか?

c:\Users\xxx\AppData\Local\Temp\m8ed4ow-.0.cs(1,32: error CS0246: The type or namespace name 'InterfaceType' could not be found (using ディレクティブまたはアセンブリ参照がありません) ?)

string code2 =
"    public class CustomClass : InterfaceType " +
"    {" +
"    }";
        // Compiler and CompilerParameters
        CSharpCodeProvider codeProvider = new CSharpCodeProvider();

        CompilerParameters compParameters = new CompilerParameters();
        compParameters.GenerateInMemory = false; //default
        //compParameters.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
        compParameters.IncludeDebugInformation = true;
        //compParameters.TempFiles.KeepFiles = true;
        compParameters.ReferencedAssemblies.Add("System.dll");

        CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");

        // Compile the code
        CompilerResults res = codeProvider.CompileAssemblyFromSource(compParameters, code2);

        // Check the compiler results for errors
        StringWriter sw = new StringWriter();
        foreach (CompilerError ce in res.Errors)
        {
            if (ce.IsWarning) continue;
            sw.WriteLine("{0}({1},{2}: error {3}: {4}", ce.FileName, ce.Line,     ce.Column, ce.ErrorNumber, ce.ErrorText);
        }

        string error = sw.ToString();
        sw.Close();

        // Create a new instance of the class 'CustomClass'
        object myClass = res.CompiledAssembly.CreateInstance("CustomClass");
4

1 に答える 1

11

肝心なのは、他のプロジェクトを CompilerParameters.ReferencedAssemblies コレクションに追加する必要があるということです。CodeDOM がアセンブリにアクセスできる必要があるため、アセンブリが GAC に存在する必要があるか、アセンブリへの完全なパスを ReferencedAssemblies の場所に追加する必要があるため、これは注意が必要です。

これを行う簡単な方法の 1 つは、CodeDOM コンパイラを実行しているプロジェクトで「InterfaceType」を含むプロジェクトを参照している場合、次のようにすることですcompilerParameters.ReferencedAssemblies.Add(typeof(InterfaceType).Assembly.Location);。そうでない場合は、CodeDOM が参照したいアセンブリを確実に見つけられるようにするための別の方法を考え出す必要があります。

于 2012-11-16T22:15:44.960 に答える