我有多个c#类,它们具有完全不同的功能,我每天都写了很多它们,我不想每次添加一个类时构建,但所有类共享一个名为Run()的函数没有参数,构造函数也从不接受参数,是否可以从路径获取ac#文件编译它然后创建它的实例并从该实例调用Run()?
我所做的一切都是为了让一个班级完成它的工作
var x = new xclass(); //the constructor never takes a param
x.Run();
但我想做的是
var x = CreateInstance(getClassbyPath("xxx.cs"));
x.Run();
答案 0 :(得分:2)
查看System.CodeDom命名空间。
答案 1 :(得分:1)
选中此Dynamic-Code-Integration-with-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;
}
更新: 另一种方法是使用插件架构来完成,开始检查this answers。您可以将插件放在一个文件夹中,检测何时添加新插件并加载并运行它们。但这意味着为每个类创建一个新的dll并实现公共接口。