【问题标题】:Can i run c# files at run time我可以在运行时运行 c# 文件吗
【发布时间】:2014-05-04 10:52:47
【问题描述】:

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

我要做的就是让一个班级做好自己的工作

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

但我想做的是

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

【问题讨论】:

  • 你为什么不想编译它们?您不能运行 C# 文件,您可以通过反射加载编译的 dll 并调用该方法。你已经看过msdn.microsoft.com/de-de/library/wccyzw83(v=vs.110).aspx了吗?
  • 你不能直接从cs文件创建实例。您需要创建输出库 (.dll) 才能使用该类。 C# 允许您从您的 cs 文件动态创建 dll。通过使用新创建的 dll,您可以使用反射创建实例。
  • @petchirajan 谢谢我现在明白了
  • 查看this similar question。那里的答案显示了如何构建通用加载机制。

标签: c#


【解决方案1】:

查看System.CodeDom 命名空间。

【讨论】:

    【解决方案2】:

    查看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 并实现通用接口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-10
      • 2019-04-16
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      相关资源
      最近更新 更多