如何使用.net核心中的反射按名称查找类的名称空间? [英] How to find namespace of class by its name using reflection in .net core?

查看:52
本文介绍了如何使用.net核心中的反射按名称查找类的名称空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个仅包含类名的字符串列表.我需要使用Activator创建它们的实例,但是它们都可以位于不同的名称空间中.类可以在将来移入另一个名称空间,因此我无法对其进行硬编码.

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. 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.

这篇关于如何使用.net核心中的反射按名称查找类的名称空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆