相关疑难解决方法(0)

如何获取泛型类型参数的类型名称?

如果我有方法签名就好

public string myMethod<T>( ... )
Run Code Online (Sandbox Code Playgroud)

我怎样才能在方法中获取作为类型参数给出的类型的名称?我想做类似的事情typeof(T).FullName,但这确实有效......

c# generics

83
推荐指数
4
解决办法
5万
查看次数

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

我需要从它的全名创建一个类型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));
}
Run Code Online (Sandbox Code Playgroud)

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

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

.net c# reflection assemblies

6
推荐指数
2
解决办法
4393
查看次数

标签 统计

c# ×2

.net ×1

assemblies ×1

generics ×1

reflection ×1