推荐答案
// www.javascriptcn.com code example
if (obj is int i)
{
Console.WriteLine($"obj is an integer: {i}");
}
else if (obj is string s)
{
Console.WriteLine($"obj is a string: {s}");
}
else
{
Console.WriteLine("obj is neither an integer nor a string");
}本题详细解读
is 表达式模式的基本用法
在 C# 7.0 及以上版本中,is 表达式模式允许你在进行类型检查的同时,将对象转换为指定类型的变量。这种模式不仅简化了代码,还提高了代码的可读性。
语法解析
if (obj is Type variable)
{
// 如果 obj 是 Type 类型,variable 将包含转换后的值
}obj:要检查的对象。Type:要检查的类型。variable:如果obj是Type类型,variable将包含转换后的值。
示例代码解析
// www.javascriptcn.com code example
object obj = 42;
if (obj is int i)
{
Console.WriteLine($"obj is an integer: {i}");
}
else if (obj is string s)
{
Console.WriteLine($"obj is a string: {s}");
}
else
{
Console.WriteLine("obj is neither an integer nor a string");
}- 在这个示例中,
obj是一个object类型的变量,其值为42。 if (obj is int i):检查obj是否是int类型,如果是,则将obj转换为int类型并赋值给变量i。else if (obj is string s):如果obj不是int类型,则检查它是否是string类型,如果是,则将obj转换为string类型并赋值给变量s。- 如果
obj既不是int也不是string类型,则执行else块中的代码。
适用场景
- 当你需要检查一个对象的类型并同时进行类型转换时,
is表达式模式非常有用。 - 它特别适用于处理多态对象或不确定类型的对象时,简化了类型检查和转换的代码。
注意事项
is表达式模式只能在 C# 7.0 及以上版本中使用。- 在使用
is表达式模式时,确保类型转换是安全的,避免运行时异常。