1
我希望調用選定txt文件中的代碼。它工作正常,直到文件內容像「文本字符串」一樣簡單。如果我將字符串參數傳遞給它,它也可以工作。但是,當我嘗試傳遞一個對象,在我的情況下,全局失敗。錯誤是:「類型或命名空間名稱‘全球’找不到(是否缺少using指令或程序集引用?)」 下面是一些代碼..從字符串調用代碼。參數不被接受
private void button1_Click(object sender, EventArgs e)
{
Scripting scriptObj = new Scripting();
scriptObj.fileName = this.openFileDialog1.FileName;
scriptObj.tekst = File.ReadAllText(this.openFileDialog1.FileName);
string exit = scriptObj.GetAction();
this.label1.Text = exit;
}
namespace WindowsFormsApplication2
{
public class Global
{
public string fileName = "test string";
}
public class Scripting
{
public string tekst = "";
public string fileName = "";
public string MyMethod1(Global obj) { return (obj.fileName); }
public string GetAction()
{
string sourceCode = @" namespace WindowsFormsApplication2 { public class Scripting { public string MyMethod (Global obj) { return (" + tekst + "); }}}";
var compParms = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true
};
var csProvider = new CSharpCodeProvider();
CompilerResults compilerResults = csProvider.CompileAssemblyFromSource(compParms, sourceCode);
if (compilerResults.Errors.HasErrors)
{
StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
foreach (CompilerError error in compilerResults.Errors)
{
errors.AppendFormat("Line {0},{1}\t: {2}\n",
error.Line, error.Column, error.ErrorText);
}
return errors.ToString();
}
else
{
Global newGlobal = new Global();
newGlobal.fileName = "TEsTfileNameToOutput";
object typeInstance = compilerResults.CompiledAssembly.CreateInstance("WindowsFormsApplication2.Scripting");
MethodInfo mi = typeInstance.GetType().GetMethod("MyMethod");
string methodOutput = (string)mi.Invoke(typeInstance, new object[]{ newGlobal });
return methodOutput;
}
}
}
}
爲什麼
public string MyMethod (Global obj) { return (" + tekst + "); }
不採取全球作爲PARAM,但它的工作原理與OK MyMethod1
public string MyMethod1(Global obj) { return (obj.fileName); }
內容選擇的文件是:obj.fileName
我應該添加什麼?我試過了:compParms.ReferencedAssemblies.Add(「Global」);和它的:「元數據文件'全局'找不到」 – NinjaOnTilt
@NinjaOnTilt:那麼你的程序集叫什麼?包含所有這些代碼的那個,也就是說。我懷疑它叫做'Global.exe'或'Global.dll'。也許'WindowsFormsApplication2',給定名稱空間名稱? (我希望你會想出一個更好的名字,介意你......) –
哈哈。抱歉,但我不知道我的程序集被稱爲什麼。我把所有的程序代碼放在那裏。它只是公共類Global public string fileName =「test string」;對我來說是' }。是:「WindowsFormsApplication2.exe」嗎? – NinjaOnTilt