【问题标题】:How to load a class from .cs file and use it in code如何从 .cs 文件加载一个类并在代码中使用它
【发布时间】:2023-03-07 05:25:01
【问题描述】:

我想从 .cs 文件加载一个类并在另一个代码中使用它。
假设我有一个 .cs 文件,其中包含这样的代码:

//some imports

public class Commands
{

     //a lot of commands

}

我正在尝试使用 CSharpCodeProvider 或其他方式从文件中加载此类并创建命令列表。

来自控制台应用程序的一段代码。

list<Commands> lst;

问题是如何动态加载 Commands 类(在运行时)(无需重新启动控制台应用程序或启动 VS)并创建命令列表?

【问题讨论】:

  • 请注意,这是一个极端的安全风险。
  • 无论这是否是一个好主意(而且我们不知道它所处的环境),这是一个有趣的问题,我希望人们不会在不解释有什么问题的情况下投反对票并逃跑问题。
  • “命令”应该是什么?在我看来,您可以定义您的 Commands 类,然后将一些 json 或其他内容反序列化到您的列表中。当然,如果您的 Commands 实际上在行为上是流动的/动态的,这显然是行不通的。
  • 当你说“很多命令”时,你到底是什么意思?什么是命令?

标签: c# .net vb.net compilation


【解决方案1】:

试试这个我整理并测试过的例子:

将 program.cs 构建为 .Net Framework Console App 在例如视觉工作室。

// program.cs
using System;
using System.IO;
using System.CodeDom.Compiler;
using System.Reflection;

namespace RuntimeCompile
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get a path to the file(s) to compile.
            FileInfo sourceFile = new FileInfo("mySource.cs");
            Console.WriteLine("Loading file: " + sourceFile.Exists);

            // Prepary a file path for the compiled library.
            string outputName = string.Format(@"{0}\{1}.dll",
                Environment.CurrentDirectory,
                Path.GetFileNameWithoutExtension(sourceFile.Name));

            // Compile the code as a dynamic-link library.
            bool success = Compile(sourceFile, new CompilerParameters()
            {
                GenerateExecutable = false, // compile as library (dll)
                OutputAssembly = outputName,
                GenerateInMemory = false, // as a physical file
            });

            if (success)
            {
                // Load the compiled library.
                Assembly assembly = Assembly.LoadFrom(outputName);

                // Now, since we didn't have reference to the library when building
                // the RuntimeCompile program, we can use reflection to create 
                // and use the dynamically created objects.
                Type commandType = assembly.GetType("Command");

                // Create an instance of the loaded class from its type information.
                object commandInstance = Activator.CreateInstance(commandType);

                // Invoke the method by name.
                MethodInfo sayHelloMethod = commandType.GetMethod("SayHello", BindingFlags.Public | BindingFlags.Instance);
                sayHelloMethod.Invoke(commandInstance, null); // no arguments, no return type
            }

            Console.WriteLine("Press any key to exit...");
            Console.Read();
        }

        private static bool Compile(FileInfo sourceFile, CompilerParameters options)
        {
            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

            CompilerResults results = provider.CompileAssemblyFromFile(options, sourceFile.FullName);

            if (results.Errors.Count > 0)
            {
                Console.WriteLine("Errors building {0} into {1}", sourceFile.Name, results.PathToAssembly);
                foreach (CompilerError error in results.Errors)
                {
                    Console.WriteLine("  {0}", error.ToString());
                    Console.WriteLine();
                }
                return false;
            }
            else
            {
                Console.WriteLine("Source {0} built into {1} successfully.", sourceFile.Name, results.PathToAssembly);
                return true;
            }
        }
    }
}

在输出目录 (bin) 中,在控制台应用程序可执行文件旁边放置一个名为 mySource.cs 的文本文件,其中包含以下内容:

// mySource.cs
using System;

internal class Program
{
    static void Main()
    {
        Console.WriteLine("Hello from mySource!");
        Console.ReadLine();
    }
}

public class Command
{
    public void SayHello()
    {
        Console.WriteLine("Hello (Command)");
    }
}

然后运行第一个控制台应用程序并观察它的输出。它应该记录“Hello (Command)”,表明代码已正确编译、加载和执行。

该示例展示了如何使用CodeDom.Compiler 在运行时编译一个 cs 文件,然后将其加载为 dll 以在其中运行代码。请注意,几乎没有实施任何错误处理。

这应该可以回答问题,但可能仍有更好的方法来处理您的用例。在插件加载的情况下,使用作为两个程序集的引用添加的接口是有意义的,以避免使用反射等。

【讨论】:

    【解决方案2】:

    可能有更好的方法来实现您的总体目标,例如依赖注入。

    但是,您可以使用 ICodeCompiler 来完成。

    看这篇文章https://support.microsoft.com/en-ca/help/304655/how-to-programmatically-compile-code-using-c-compiler

    【讨论】:

      【解决方案3】:

      要从另一个 c# 类加载 c# 类,您需要使用“使用”

      using Commands;
      public class class1
      {
          private list<Commands>lst;
          //...
      }
      

      【讨论】:

        猜你喜欢
        • 2011-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多