代码之家  ›  专栏  ›  技术社区  ›  asgerhallas

getInterfaces()返回fullname=null的通用接口类型

  •  2
  • asgerhallas  · 技术社区  · 14 年前

    Can anyone explain to me why GetInterfaces() in the below code returns an interface type that has 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'
    

    请告诉我:)

    2 回复  |  直到 6 年前
        1
  •  7
  •   Lars Udengaard    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

    Type.FullName is null if the current instance represents a generic type parameter, an array type, pointer type, or byref type based on a type parameter, or a generic type that is not a generic type definition but contains unresolved type parameters.

    下面是一个例子 Type.FullName null 从文件中总结:

        [Fact]
        public void FullNameOfUnresolvedGenericArgumentIsNull()
        {
            Type openGenericType = typeof(Nullable<>);
            Type typeOfUnresolvedGenericArgument = openGenericType.GetGenericArguments()[0];
    
            Assert.Null(typeOfUnresolvedGenericArgument.FullName);
        }
    
        2
  •  0
  •   Skarllot    6 年前

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

    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);
    }