Type.FullName的MSDN文档指出该属性返回以下内容:
如果当前实例表示泛型类型参数、数组类型、基于类型参数的指针类型或byref类型,或者是不是泛型类型定义但包含未解析类型参数的泛型类型,则返回null。
我数了一下,这里有五种情况,每一种都更加不清晰。以下是我构造每种情况的示例的尝试。
这是输出结果。
如果当前实例表示泛型类型参数、数组类型、基于类型参数的指针类型或byref类型,或者是不是泛型类型定义但包含未解析类型参数的泛型类型,则返回null。
我数了一下,这里有五种情况,每一种都更加不清晰。以下是我构造每种情况的示例的尝试。
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication {
public static class Program {
public static void Main(string[] args) {
GenericTypeParameter();
ArrayType();
PointerType();
ByRefTypeBasedOnTypeParameter();
NongenericTypeDefinitionWithUnresolvedTypeParameters();
Console.ReadKey();
}
public static void GenericTypeParameter() {
var type = typeof(IEnumerable<>)
.GetGenericArguments()
.First();
PrintFullName("Generic type parameter", type);
}
public static void ArrayType() {
var type = typeof(object[]);
PrintFullName("Array type", type);
}
public static void PointerType() {
var type = typeof(int*);
PrintFullName("Pointer type", type);
}
public static void ByRefTypeBasedOnTypeParameter() {
var type = null;
PrintFullName("ByRef type based on type parameter", type);
}
private static void NongenericTypeDefinitionWithUnresolvedTypeParameters() {
var type = null;
PrintFullName("Nongeneric type definition with unresolved type parameters", type);
}
public static void PrintFullName(string name, Type type) {
Console.WriteLine(name + ":");
Console.WriteLine("--Name: " + type.Name);
Console.WriteLine("--FullName: " + (type.FullName ?? "null"));
Console.WriteLine();
}
}
}
这是输出结果。
Generic type parameter:
--Name: T
--FullName: null
Array type:
--Name: Object[]
--FullName: System.Object[]
Pointer type:
--Name: Int32*
--FullName: System.Int32*
ByRef type based on type parameter:
--Name: Program
--FullName: ConsoleApplication.Program
Nongeneric type definition with unresolved type parameters:
--Name: Program
--FullName: ConsoleApplication.Program
我在五次尝试中只成功了一次,有两次是“空白”的。
问题
有人能够修改我的代码并举出 Type.FullName 可能为空的每种情况的简单例子吗?