加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 当泛型参数来自多个程序集时,按名称加载泛型类型

发布时间:2020-12-15 18:10:33 所属栏目:百科 来源:网络整理
导读:我需要从它的全名创建一个类型Ex:“System.String”或“Tuple’2 [string,Mytype]”. 字符串中没有关于程序集的信息. 这是代码的样子. private static Type LoadType(string typeName){ // try loading the type Type type = Type.GetType(typeName,false);
我需要从它的全名创建一个类型Ex:“System.String”或“Tuple’2 [string,Mytype]”.
字符串中没有关于程序集的信息.
这是代码的样子.
private static Type LoadType(string typeName)
{
    // try loading the type
    Type type = Type.GetType(typeName,false);

    if (type != null)
        return type;

    // if the loading was not successfull iterate all the referenced assemblies and try to load the type.
    Assembly asm = Assembly.GetEntryAssembly();
    AssemblyName[] referencedAssemblies = asm.GetReferencedAssemblies();
    foreach (AssemblyName referencedAssemblyName in referencedAssemblies)
    {
        type = referencedAssembly.GetType(typeName,false);
        if (type != null)
            return type;
    }
    throw new TypeLoadException(string.Format("Could not load the Type '{0}'",typeName));
}

当类型不是通用的时,此方法有效.但是对于泛型类型,遍历程序集总是失败,因为没有程序集包含构建类型所需的所有定义.

有没有办法在调用GetTypes时为类型解析提供多个程序集?

解决方法

你将不得不以我认为的艰难方式去做.幸运的是,这并不难.很简单:

>将类型名称解析为类型定义和泛型类型参数.>获取泛型类型定义对象>获取每个泛型类型参数的类型对象>使用类型定义对象上的MakeGenericType方法,从泛型类型定义和泛型类型参数构造泛型类型.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读