2016-11-11 30 views
1

我在一個研究小組工作,並且我的任務是爲腳本功能添加數據採集程序。理想情況下,我希望能夠在數據採集軟件運行時編寫腳本(並將這些腳本保存爲移動中的文件)。命令行也可能很好。我對C#並不是很有經驗,但是我在其他語言(Objective-C,Python)中有相當多的編碼經驗。我看到這個鏈接https://blogs.msdn.microsoft.com/cdndevs/2015/12/01/adding-c-scripting-to-your-development-arsenal-part-1/詳細描述了「Roselyn腳本包」,但我不確定這是否是我的最佳選擇。爲現有的C#項目添加腳本功能

任何人都可以提出獲得完整腳本功能的最簡單方法嗎? (我試圖避免在這裏失去幾個月的生命= p)。以/ advice開始的鏈接非常感謝。

謝謝!

回答

0

您爲我發佈了一個有趣的鏈接,因爲我幾周前剛創建了類似的東西,但尚未實現。我的目標是在網頁上創建一個C#「即時」控制檯。

對於以編程方式加載某些組件有一些小問題,必須明確引用它們。

這是後面的代碼,請稍後發佈您的解決方案,我有興趣知道。

這樣就可以在運行時編寫c#代碼並獲得一個字符串返回值。

protected void getImmediateResult_Click(object sender, EventArgs e) 
    { 

     //building the code 
     string source = @"using System; 
     class MyType{ 
     public static String Evaluate(){ 
     <!expression!> 
     }}"; 

     string expression = this.txtimmediate.Text; 
     string finalSource = source.Replace("<!expression!>", expression); 
     textcodeCheck.Text = finalSource; 
     var compileUnit = new CodeSnippetCompileUnit(finalSource); 

     //preparing compilation 
     CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); 

     // Create the optional compiler parameters 

     //this correctly references the application but no System.Web etc 
     string[] refArray = new string[2]; 

     UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase); 
     refArray[0] = uri.Path; 

     //this works 
     refArray[1] = "System.Web" + ".dll"; 

     ////NOT WORKING for non microsoft assemblies 
     //var allRefs = Assembly.GetExecutingAssembly().GetReferencedAssemblies(); 
     //string[] refArray = new string[allRefs.Length + 1]; 
     //int i = 1; 
     //foreach (AssemblyName refer in allRefs) 
     //{ 
     // refArray[i] = refer.Name + ".dll"; 
     // i++; 
     //} 

     var compilerParameters = new CompilerParameters(refArray); 

     CompilerResults compilerResults = provider.CompileAssemblyFromDom(compilerParameters, compileUnit); 
     if (compilerResults.Errors.Count > 0) 
     { 
      //1st error 
      this.txtResult.Text = compilerResults.Errors[0].ErrorText; 
      return; 
     } 

     //running it 
     Type type = compilerResults.CompiledAssembly.GetType("MyType"); 
     MethodInfo method = type.GetMethod("Evaluate"); 
     String result = (String)method.Invoke(null, null); 


     this.txtResult.Text = result; 
    } 
+0

,'CSharpCodeProvider '等),你不需要那些駭客的字符串來源,你可以通過代碼構建樣板。 – Kroltan

+0

@Kroltan你確定嗎?我只是不想每次鍵入類的語法。 – user6788933

+1

我的意思是,樣板可以用代碼構造,而不是從一個字符串中解析出來並替換。通過這種方式,您可以在代碼段中更準確地報告錯誤,而不是周圍的樣板。示例(使用C#6,但可輕鬆轉換爲其他版本):http://pastebin.com/5w86FrVb – Kroltan

0

如果你願意使用IronPython的,您可以直接在C#中執行腳本:如果您在使用`CodeDom`(`CodeSnippetCompileUnit`

using IronPython.Hosting; 
using Microsoft.Scripting.Hosting; 

private static void doPython() 
{ 
    ScriptEngine engine = Python.CreateEngine(); 
    engine.ExecuteFile(@"test.py"); 
} 

Get IronPython here.