我有一个 C# class ,我必须获得...的类型,但我只有名称(单个名称)作为字符串

I have a C# class which i have to get the type of... but i only have the name(single name) as a string

我有一个 class 名叫 Hacker 我在 中有一个 class 间谍,我必须做一个采用 Hacker class 的名称(单个名称)的方法,但是让字符串“Hacker”做一些工作并且 return 它作为一个字符串,我想在我的主要方法中通过这段代码完成工作:

        Spy spy = new Spy();
        string result = spy.AnalyzeAccessModifiers("Hacker");
        Console.WriteLine(result);

在我尝试的 AnalyzeAccessModifiers 方法中:

public string AnalyzeAccessModifiers(string className)
    {
     // i need to get some job done with:
     Type type = Type.GetType(classname);//but it need the fully qualified name for that.
     // so i tried:
     Type type = typeof(className); // but it does not work with string...
    }

当我只有名称作为字符串时,有什么办法可以做到这一点...我能想到的唯一方法是使用实​​际的 class 名称作为类型而不是字符串但这不在我的任务描述中...

遗憾的是 Type.GetType(string) 在给你结果之前对它所需要的细节非常挑剔。如果您要查找的类型在当前正在执行的程序集(或 mscorlib/System.Private.CoreLib)中,那么将得到一个完全指定的名称(包括命名空间)的结果。如果它在不同的程序集中,那么您需要指定程序集名称。

Type type = null;

// Fails
type = Type.GetType("String");

// Succeeds from core library
type = Type.GetType("System.String");

// Fails (loading from a different assembly)
type = Type.GetType("System.Text.Json.JsonSerializer");

// Succeeds (.NET 6.0)
type = Type.GetType("System.Text.Json.JsonSerializer, System.Text.Json");

这一切都很好,直到您试图找到一种类型,而您恰好拥有一条关于该类型的信息:class 名称。如果没有命名空间和程序集名称,您将不得不枚举每种类型,直到找到您要查找的内容...

static Type? TypeFromName(string name) =>
    // All loaded assemblies
    AppDomain.CurrentDomain.GetAssemblies()
    // All types in loaded assemblies
    .SelectMany(asm => asm.GetTypes())
    // Return first match
    .FirstOrDefault(type => type.Name == name);

很简单,是的。快速地?甚至不遥远。但是您只需搜索一次,然后将结果缓存起来供以后使用。