这取决于类是哪个程序集。如果它在mscorlib 或调用程序集,你所需要的就是
Type type = Type.GetType("namespace.class");
但如果它是从其他程序集引用的,您需要这样做:
Assembly assembly = typeof(SomeKnownTypeInAssembly).Assembly;
Type type = assembly.GetType("namespace.class");
//or
Type type = Type.GetType("namespace.class, assembly");
如果您只有类名“MyClass”,那么您必须以某种方式获取命名空间名称(或命名空间名称和程序集名称,以防它是引用程序集)并将其与类名连接起来。比如:
//if class is in same assembly
var namespace = typeof(SomeKnownTypeInNamespace).Namespace;
Type type = Type.GetType(namespace + "." + "MyClass");
//or for cases of referenced classes
var assembly = typeof(SomeKnownTypeInAssembly).Assembly;
var namespace = typeof(SomeKnownTypeInNamespace).Namespace;
Type type = assembly.GetType(namespace + "." + "MyClass");
//or
Type type = Type.GetType(namespace + "." + "MyClass" + ", " + assembly.GetName().Name);
如果您一无所有(甚至不知道程序集名称或命名空间名称),而只有类名,那么您可以查询整个程序集以选择匹配的字符串。 但这应该会慢很多:
Type type = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.FirstOrDefault(x => x.Name == "MyClass");
请注意,这会返回第一个匹配的类,因此如果您在程序集/命名空间中有多个具有相同名称的类,则不需要非常准确。 在任何情况下,缓存值在这里都是有意义的。 稍微快一点的方法是假设有一个默认命名空间:
Type type = AppDomain.CurrentDomain.GetAssemblies()
.Select(a => new { a, a.GetTypes().First().Namespace })
.Select(x => x.a.GetType(x.Namespace + "." + "MyClass"))
.FirstOrDefault(x => x != null);
但这又是一个假设,即您的类型将与程序集中的其他随机类具有相同的命名空间;太脆,不太好。
如果您想要其他域的类,您可以获取所有应用程序域的列表,遵循this link. 然后您可以对每个域执行如上所示的相同查询。如果尚未加载类型所在的程序集,则必须使用 Assembly.Load、Assembly.LoadFrom 等手动加载它。