从文件路径获取类名

本文关键字:获取 路径 文件 | 更新日期: 2023-09-27 18:06:36

我有一个读取文件夹并将路径保存到数组列表的系统。这个文件夹包含一堆类文件"。cs",所有这些类实现一个名为BaseScript的接口。

我试图找到类名称,以便我可以调用类方法,但您应该能够定期将类文件添加到此文件夹,因此我无法硬编码要创建的对象。

。我有一个名为"Manufacturing.cs"的文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LLS
{
    class Manufacturing : BaseScript
    {
        public void init()
        {
            Console.WriteLine("Manufacturing...");
        }
        public void uninit() { }
        public void recomp() { }
    }
}

它实现了"BaseScript":

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LLS
{
    public interface BaseScript
    {
        void init();
        void uninit();
        void recomp();
    }
}

我需要能够使用路径:"'Scripts'Manufacturing.cs"来调用像

这样的东西
BaseScript[] s = {new "Manufacturing class name"}
我知道一定有什么迂回的方法来做这件事。我如何找到类名,然后从该类创建实例?

从文件路径获取类名

如果你的类在同一个程序集中,那么你可以使用Activator.CreateInstance创建对象的实例。我没在我这边试过你的代码。所以选角可能行不通。仔细检查这段代码:

BaseScript s = (BaseScipt)Activator.CreateInstance(null, "Namespace.TestClass");

由于某些原因,我误以为您有dll文件而不是cs文件。

正如其他人所说,你没有正确地解释这个场景。但从我的理解,你可能是实现一个插件类型的模式在这里。为了调用你以后可能添加的c#类的方法,你需要遍历文件夹,获得*.cs文件,编译它们,然后使用反射,加载程序集并创建一个你知道存在的类的实例(你应该事先知道类的完全限定名)。最后,您应该找到要调用的方法,然后使用反射调用它。下面是一些帮助您入门的代码:

Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters();
parameters.GenerateInMemory = true;
//You should add all referenced assembiles needed for the cs file here
//parameters.ReferencedAssemblies.Add();
var files = new System.IO.DirectoryInfo("Scripts").GetFiles("*.cs");
foreach (System.IO.FileInfo file in files)
{
    System.CodeDom.Compiler.CompilerResults result = 
        provider.CompileAssemblyFromSource(parameters, new[] { System.IO.File.ReadAllText(file.FullName) });
    object instance = result.CompiledAssembly.CreateInstance(file.Name);
    if (instance is BaseScript)
    {
        //Do processing on (BaseScript)instance
    }
}