GetInterfaces()返回FullName = null的泛型接口类型

问题描述 投票:2回答:2

任何人都可以向我解释为什么下面的代码中的GetInterfaces()返回一个FullName = null的接口类型?

public class Program
{
    static void Main(string[] args)
    {
        Type[] interfaces = typeof (Data<>).GetInterfaces();
        foreach (Type @interface in interfaces)
        {
            Console.WriteLine("Name='{0}' FullName='{1}'", @interface.Name, @interface.FullName ?? "null");
        }
    }
}

public class Data<T> : IData<T>
{
    public T Content { get; set; }
}

public interface IData<T>
{
    T Content { get; set; }
}

该计划的输出是:

Name=IData`1' FullName='null'

我有点期待:

Name=IData`1'
FullName='ConsoleApplication2.IData`1'

请赐教:)

c# .net generics reflection
2个回答
7
投票

http://blogs.msdn.com/b/haibo_luo/archive/2006/02/17/534480.aspx

更新:Microsoft文档已得到改进:

https://msdn.microsoft.com/en-us/library/system.type.fullname.aspx

如果当前实例表示基于类型参数的泛型类型参数,数组类型,指针类型或byref类型,或者不是泛型类型定义但包含未解析类型参数的泛型类型,则Type.FullName为null。

这是一个Type.FullNamenull的情况的例子,从文档中归结为:

    [Fact]
    public void FullNameOfUnresolvedGenericArgumentIsNull()
    {
        Type openGenericType = typeof(Nullable<>);
        Type typeOfUnresolvedGenericArgument = openGenericType.GetGenericArguments()[0];

        Assert.Null(typeOfUnresolvedGenericArgument.FullName);
    }

0
投票

您可以创建一个扩展方法来修复类型引用:

public static Type FixTypeReference(this Type type)
{
    if (type.FullName != null)
        return type;

    string typeQualifiedName = type.DeclaringType != null
        ? type.DeclaringType.FullName + "+" + type.Name + ", " + type.Assembly.FullName
        : type.Namespace + "." + type.Name + ", " + type.Assembly.FullName;

    return Type.GetType(typeQualifiedName, true);
}
© www.soinside.com 2019 - 2024. All rights reserved.