C# 类型检查
上次修改于 2024 年 1 月 21 日
在本文中,我们将展示如何在 C# 中使用 typeof 和 is 运算符以及 GetType 方法来检查类型。
在 C# 中,每个变量和表达式都有一个类型。 类型 是一组值以及允许对这些值执行的操作。
类型存储以下信息
- 该类型的变量所需的存储空间
- 该类型的最大值和最小值
- 类型成员,例如字段或方法
- 它继承的基类型
- 已实现的接口
- 允许的操作
编译器使用这些信息来确保类型安全的操作。
System.Type 类表示类型声明。
我们可以使用 typeof 运算符、is 运算符或 GetType 方法来检查类型。 typeof 运算符获取类型的 System.Type 实例。 该运算符在编译时检查类型。 它仅适用于类型,不适用于变量。
GetType 方法获取当前对象实例的类型。 它在运行时检查类型。
is 运算符检查实例是否在类型的继承树中。 此外,它允许类型安全的强制转换。
C# typeof 示例
第一个示例使用 typeof 运算符打印内置类型的 System.Type。
Type t = typeof(int); Console.WriteLine(t); Console.WriteLine(typeof(List<int>)); Console.WriteLine(typeof(string)); Console.WriteLine(typeof(double)); Console.WriteLine(typeof(float)); Console.WriteLine(typeof(decimal)); Console.WriteLine(typeof(User)); record User(string Name, string Occupation);
该示例打印 int、List<int>、string、double、float、decimal 和 User 的 System.Type。
$ dotnet run System.Int32 System.Collections.Generic.List`1[System.Int32] System.String System.Double System.Single System.Decimal User
C# GetType 示例
以下示例检查三个变量的类型。
int x = 34;
string word = "falcol";
decimal i = 23.54m;
if (x.GetType() == typeof(int))
{
Console.WriteLine("x has int type");
}
if (word.GetType() == typeof(string))
{
Console.WriteLine("word has string type");
}
if (i.GetType() == typeof(decimal))
{
Console.WriteLine("i has decimal type");
}
我们定义一个整数、字符串和十进制变量。 我们使用 GetType 方法在运行时检查类型。
$ dotnet run x has int type word has string type i has decimal type
C# is 运算符
is 运算符检查对象是否与给定类型兼容,即它是否在其继承树中。
Base _base = new();
Derived derived = new();
Console.WriteLine(_base is Base);
Console.WriteLine(_base is object);
Console.WriteLine(derived is Base);
Console.WriteLine(_base is Derived);
class Base { }
class Derived : Base { }
我们从用户定义的类型创建两个对象。
class Base {}
class Derived : Base {}
我们有一个 Base 类和一个 Derived 类。 Derived 类继承自 Base 类。
Console.WriteLine(_base is Base); Console.WriteLine(_base is object);
Base 等于 Base,因此第一行打印 True。 Base 也与 Object 类型兼容。 这是因为每个类都继承自所有类的母类 - Object 类。
Console.WriteLine(derived is Base); Console.WriteLine(_base is Derived);
派生对象与 Base 类兼容,因为它显式地继承自 Base 类。 另一方面,_base 对象与 Derived 类没有任何关系。
$ dotnet run True True True False
C# 使用 is 进行类型安全检查
我们可以使用 is 运算符执行类型安全的强制转换。
object[] vals = [
12, "falcon", 3, 1, true, 20
];
foreach (var e in vals)
{
if (e is int val)
{
Console.WriteLine($"{val} powered is {val * val}");
}
}
我们有一个对象数组。 对于所有整数,我们计算其幂。
if (e is int val)
{
Console.WriteLine($"{val} powered is {val * val}");
}
如果转换是可能的,则 is 运算符会创建一个 int 类型的局部变量 val。
$ dotnet run 12 powered is 144 3 powered is 9 1 powered is 1 20 powered is 400
或者,我们可以使用 LINQ 的 OfType 方法来完成这项工作。
object[] vals = [
12, "falcon", 3, 1, true, 20
];
var res = vals.OfType<int>();
foreach (var e in res)
{
Console.WriteLine($"{e} powered is {e * e}");
}
OfType 方法基于指定的类型过滤 IEnumerable 的元素。
C# 检查装箱值
使用 is 运算符,我们可以检查装箱值的实际类型。 装箱是将值类型转换为 object 类型的过程。
object o = 12; Console.WriteLine(o is int); Console.WriteLine(o is double); object o2 = "falcon"; Console.WriteLine(o2 is string); Console.WriteLine(o2 is char);
该示例确定两个装箱值的实际类型。
$ dotnet run True False True False
C# switch 表达式类型模式
类型可以是 switch 表达式的模式。
int age = 23;
string name = "Peter";
List<string> colors = ["blue", "khaki", "orange"];
int[] nums = [1, 2, 3, 4, 5];
Console.WriteLine(check(age));
Console.WriteLine(check(name));
Console.WriteLine(check(colors));
Console.WriteLine(check(nums));
object check(object val) => val switch
{
int => "integer",
string => "string",
List<string> => "list of strings",
Array => "array",
_ => "unknown"
};
在该示例中,我们使用 switch 表达式检查变量的类型。
$ dotnet run integer string list of strings array
来源
在本文中,我们展示了如何在 C# 中使用 typeof、is 和 GetType 检查类型。
作者
列出所有 C# 教程。