您爲我發佈了一個有趣的鏈接,因爲我幾周前剛創建了類似的東西,但尚未實現。我的目標是在網頁上創建一個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;
}
,'CSharpCodeProvider '等),你不需要那些駭客的字符串來源,你可以通過代碼構建樣板。 – Kroltan
@Kroltan你確定嗎?我只是不想每次鍵入類的語法。 – user6788933
我的意思是,樣板可以用代碼構造,而不是從一個字符串中解析出來並替換。通過這種方式,您可以在代碼段中更準確地報告錯誤,而不是周圍的樣板。示例(使用C#6,但可輕鬆轉換爲其他版本):http://pastebin.com/5w86FrVb – Kroltan