1

外部ファイルを読み取ってコンパイルしようとしています (現在は文字列定数になっています)。

外部コードで基本的なプリミティブを使用できますが、怒らずにクラスタイプを渡す方法がわからないようです-これが私が持っているものです(使用行を除く)

class myClass
{
    public int x;
    public myClass(int n)
    {
        x = n;
    }
}
class Program
{
    static void Main(string[] args)
    {
        string source =
        @"
           namespace ConsoleApplication1
           {
               public class Bar
               {
                   public int getNumber(myClass c)
                   {
                       return c.x;
                   }
              }
          }";     
            Dictionary<string, string> providerOptions = new Dictionary<string, string>
            {
                {"CompilerVersion", "v3.5"}
            };
            CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
            CompilerParameters compilerParams = new CompilerParameters
            {
                GenerateInMemory = true,
                GenerateExecutable = false
            };
            CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
            if (results.Errors.Count != 0)
                throw new Exception("Failed");
        object o = results.CompiledAssembly.CreateInstance("ConsoleApplication1.Bar");
        MethodInfo mi = o.GetType().GetMethod("getNumber");
        object[] param = new object[1];
        myClass c = new myClass(5);
        param[0] = c;
        int myInt = (int)mi.Invoke(o, param);
        Console.Write(myInt);
        Console.ReadLine();
    }
}

助けていただければ幸いです

4

1 に答える 1

0

コードを見ると、「新しい」アセンブリ (文字列バージョン) が現在実行中のアセンブリ (同じ名前空間かどうか) を認識していないことが問題のようです。解決策は、現在実行中のアセンブリを参照することです。compilerParams の初期化の直後に次の行を追加します。

compilerParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

また、コードを起動したときに、myClass 宣言を public に変更しました。

于 2013-12-03T04:18:42.427 に答える