2016-11-26 56 views
0

我得到錯誤:找不到類型'SimpleScript.Generator'的構造函數。C#CodeProvider錯誤:未找到類型的構造函數

我嘗試傳遞正確的參數,但我仍然得到這個錯誤,這是我的源代碼,而腳本是一段非常簡單的代碼,可以生成元素頭部和正文的數組。它也被成功編譯,但它會在執行線上拋出錯誤。

string source = @" 

using System; 
using MSiteDLL; 
namespace SimpleScript 
{ 
    public static class Generator 
    { 
     public static Document Generate(Data server) 
     { 
      "+script+ @" 
        Block[] blocks = { 
        new Block(""head"", head), 
        new Block(""body"", body), 
        }; 
      return new Document(blocks); 
     } 
    } 
} 

"; 
      Dictionary<string, string> providerOptions = new Dictionary<string, string> 
       { 
        {"CompilerVersion", "v4.0"} 
       }; 
      CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions); 

      CompilerParameters compilerParams = new CompilerParameters 
      { 
       GenerateInMemory = true, 
       GenerateExecutable = false, 
       ReferencedAssemblies = { 
     "System.dll", 
     "System.Core.dll", 
     "MSiteDLL.dll", 
    } 
      }; 

      CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source); 

      if (results.Errors.Count != 0) 
      { 
       string output = ""; 
       foreach (CompilerError y in results.Errors) 
       { 
        output += y.ErrorText + Environment.NewLine; 
       } 
       throw new Exception("Compile failed:" + output); 
      } 
      object o = results.CompiledAssembly.CreateInstance("SimpleScript.Generator"); 
      MethodInfo mi = o.GetType().GetMethod("Generate"); 
      Data[] parametersArray = new Data[] { server }; 
      Document x = (Document)mi.Invoke(o, parametersArray); 
      return x; 
+3

你試圖實例化一個'static'類,你不能這樣做。 – Mat

+0

我刪除了靜態keywrod,它工作。 –

+0

謝謝你的幫助。 :D –

回答

3

由於您的類是靜態的,因此應該以靜態方式調用該方法。 因此,首先,刪除此行:

object o = results.CompiledAssembly.CreateInstance("SimpleScript.Generator"); 

,並使用這些調用:

MethodInfo mi = Type.GetType("SimpleScript.Generator").GetMethod("Generate"); 
Data[] parametersArray = new Data[] { server }; 
Document x = (Document)mi.Invoke(null, parametersArray); 
+0

我會盡快接受這個答案。 –

+0

做了一個快速編輯,因爲我忘記從'MethodInfo'行中刪除'o'。使用'Type.GetType(「SimpleScript.Generator」)'應該得到你的類型。 – Mat

相關問題