我可以在运行时运行c#文件吗

本文关键字:文件 运行 运行时 我可以 | 更新日期: 2023-09-27 17:53:18

我有多个c#类,它们有完全不同的功能,我每天都会写很多,我不想每次添加一个类都构建,但所有类都共享一个名为Run((的函数,它不需要参数,构造函数也从不需要参数,是否可以从路径中获取一个c#文件?编译它,然后创建它的实例并从该实例调用Run((?

我所做的就是让一个班级完成它的工作

var x = new xclass(); //the constructor never takes a param
x.Run();

但我想做的是

var x = CreateInstance(getClassbyPath("xxx.cs"));
x.Run();

我可以在运行时运行c#文件吗

查看System.CodeDom命名空间。

检查与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并实现公共接口。