简体   繁体   English

如何使用.net core中的反射按名称查找类的命名空间?

[英]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.

相关问题 如何使用Reflection获取命名空间,类,方法及其参数 - How to get namespace, class, methods and its arguments with Reflection 使用.net反射来查找共同的祖先类 - Using .net reflection to find a common ancestor class 在.NET Core中使用反射 - Using Reflection in .NET Core 使用反射的子类的类属性名称及其数据类型 - Class property name and its data type for sub class using Reflection 如何使用反射在 ASP.NET 内核中使用自己的接口注册多个实现? - How to register multiple implementations with its own interface in ASP.NET Core using Reflection? 如何使用.net中的反射获取对象名称? - How to fetch object name using reflection in .net? 查找类以按名称实例化而无需命名空间或程序集? (。净) - Find class to instantiate by name without namespace or assembly? (.NET) C#/ .NET如何从类名中找到包含的命名空间 - C#/.NET How do I find the containing namespace from a class name 有没有一种方法可以通过将某个类/接口/…用其名称空间而不是使用指令“ using namespace_name”封闭起来来引用它? - Is there a way to reference a certain class/interface/… by enclosing it with its namespace rather than a using directive “using namespace_name”? 如何使用反射获取类的所有静态属性及其值 - How to get all static properties and its values of a class using reflection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM