[英]Can i run c# files at run time
我有多個C#類,它們具有完全不同的功能,並且我每天都會編寫很多它們,並且我不想每次添加一個類時都進行構建,但是所有類都共享一個稱為Run()的函數,並且不帶任何參數構造函數也永遠不會使用參數,是否可以從路徑中獲取ac#文件,然后對其進行編譯,然后使其實例並從該實例中調用Run()?
我要做的是讓一個班級做好自己的工作
var x = new xclass(); //the constructor never takes a param
x.Run();
但是我想做的是
var x = CreateInstance(getClassbyPath("xxx.cs"));
x.Run();
看一下System.CodeDom命名空間。
選中此動態代碼集成代碼域
上面鏈接的小例子
class Program
{
static void Main( string[] args )
{
Test1();
}
private static void Test1()
{
//
// Create an instance of type Foo and call Print
//
string FooSource = @"
class Foo
{
public void Print()
{
System.Console.WriteLine(""Hello from class Foo"");
}
}";
Assembly assembly = CompileSource(FooSource);
object myFoo = assembly.CreateInstance("Foo");
// myFoo.Print(); // - Print not a member of System.Object
// ((Foo)myFoo).Print(); // - Type Foo unknown
}
}
private static Assembly CompileSource( string sourceCode )
{
CodeDomProvider cpd = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("ClassLibrary1.dll");
cp.GenerateExecutable = false;
// Invoke compilation.
CompilerResults cr = cpd.CompileAssemblyFromSource(cp, sourceCode);
return cr.CompiledAssembly;
}
更新:您可以通過使用插件架構來完成此操作的另一種方式,即開始檢查此答案 。 您可以將插件放在文件夾中,並檢測何時添加了新插件,然后加載並運行它們。 但這意味着為您的每個類創建一個新的dll並實現公共接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.