[英]How to find namespace of class by its name using reflection in .net core?
I have a list of string with only classes names. 我有一个只有类名的字符串列表。 I need to create instances of them using Activator, but all of them can be in diffrent namespaces.
我需要使用Activator创建它们的实例,但所有这些实例都可以在不同的命名空间中。 Classes can be move into another namespace in the future so i can't hardcode it.
将来可以将类移动到另一个命名空间中,因此我无法对其进行硬编码。
If you know that you'll never have multiple types with the same name residing in the different namespaces, you can just iterate over all types in the assembly and filter on type name. 如果您知道您将永远不会有多个具有相同名称的类型驻留在不同的名称空间中,您可以只迭代程序集中的所有类型并过滤类型名称。 For example, this works:
例如,这有效:
var typenames = new[] { "String", "Object", "Int32" };
var types = typeof(object).GetTypeInfo().Assembly
.GetTypes()
.Where(type => typenames.Contains(type.Name))
.ToArray(); // A Type[] containing System.String, System.Object and System.Int32
This won't necessarily break if you have multiple types with the same name, but you'll get all of them in the list. 如果您有多个具有相同名称的类型,则不一定会中断,但您将在列表中获得所有类型。
You can get all the types of an assembly and find the one with the name in question. 您可以获取程序集的所有类型,并找到具有相关名称的程序集。
var type = assembly.GetTypes().FirstOrDefault(x => x.Name == name);
Note: the name may not be unique. 注意:名称可能不是唯一的。 In such a case, you don't have a chance to find the correct type, unless you can have some guess about the namespace 8e.g.
在这种情况下,您没有机会找到正确的类型,除非您可以对命名空间8e.g进行一些猜测。 list of possible namespaces, "blacklist" of namespaces etc.)
可能的命名空间列表,命名空间的“黑名单”等)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.