📜  获取类型名称 C# (1)

📅  最后修改于: 2023-12-03 14:57:17.062000             🧑  作者: Mango

获取类型名称 C#

在 C# 中,我们可以使用 typeof.GetType() 方法来获取类型的名称。类型名称是指类、结构、接口、枚举等类型的名称。

typeof

typeof 关键字可以获取一个类型的 System.Type 对象,进而获取类型的名称。

Type type = typeof(string);
string typeName = type.Name;
Console.WriteLine(typeName); // 输出:String

.Name 属性返回类型的名称,可以是简单名称或完全限定名称。

Type type = typeof(System.Collections.Generic.List<>);
string typeName = type.Name;
Console.WriteLine(typeName); // 输出:List`1
.GetType()

我们可以通过 .GetType() 方法来获取一个对象的类型。

string str = "Hello World!";
Type type = str.GetType();
string typeName = type.Name;
Console.WriteLine(typeName); // 输出:String

.GetType() 方法获取的是对象的运行时类型,因此可以获取实例对象的实际类型。如果对象为 null,则该方法返回 null。

string str = null;
Type type = str.GetType(); // 抛出异常:NullReferenceException
完全限定名称

完全限定名称包括命名空间和类型名称。

Type type = typeof(System.Collections.Generic.List<>);
string fullName = type.FullName;
Console.WriteLine(fullName); // 输出:System.Collections.Generic.List`1

如果是嵌套类型,完全限定名称也包括所有嵌套类型的名称。

Type type = typeof(System.Collections.Generic.Dictionary<,>.Enumerator);
string fullName = type.FullName;
Console.WriteLine(fullName); // 输出:System.Collections.Generic.Dictionary`2+Enumerator