我想要在string中只给出类型名称的System.Type。
例如,如果我有一个对象:
MyClass abc = new MyClass();然后我可以说:
System.Type type = abc.GetType();但如果我所拥有的只是:
string className = "MyClass";发布于 2013-12-06 02:34:08
这取决于类是哪个程序集。如果是在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等手动加载它。
发布于 2008-10-07 15:42:24
Type type = Type.GetType("foo.bar.MyClass, foo.bar");MSDN。确保名称为Assembly Qualified。
发布于 2008-10-07 16:51:08
要在获取类型后创建类的实例,并调用方法-
Type type = Type.GetType("foo.bar.MyClass, foo.bar");
object instanceObject = System.Reflection.Activator.CreateInstance(type);
type.InvokeMember(method, BindingFlags.InvokeMethod, null, instanceObject, new object[0]);https://stackoverflow.com/questions/179102
复制相似问题