[英]What does this syntax do? if(obj is SomeType obj2)
I'm starting to see these statements and I am trying to wrap my head around these kind of statements. 我开始看到这些陈述,我试图围绕这些陈述。
if (obj is SomeAuto car)
{
//Do stuff
}
If I understand correctly we basically are casting obj into the variable car which would be a type "SomeAuto"? 如果我理解正确,我们基本上将obj转换为变量汽车,这将是一个类型“SomeAuto”?
1) What is the official terminology of this statement? 1)本声明的官方术语是什么?
2) What would happen if I wanted to change the if statement to conditionally execute for a particular reason? 2)如果我想将if语句更改为因特定原因有条件执行会发生什么?
For example say SomeAuto is a base class and I only wanted a certain type of auto, or say I want all of the SomeAuto except maybe one particular kind. 例如,说SomeAuto是一个基类,我只想要某种类型的汽车,或者说我想要所有的SomeAuto,除了可能是一种特殊类型。
This if statement is using the is
expression added in C# 7.0 under pattern matching . 此if语句使用在模式匹配下在C#7.0中添加的
is
表达式。 Docs specify that: 文档指定:
The is pattern expression extends the familiar is operator to query an object beyond its type.
is模式表达式扩展了熟悉的is运算符,以查询超出其类型的对象。
It enables you to check if obj
is of a specific type and also assigns the casted result into a variable. 它使您能够检查
obj
是否属于特定类型,并将转换结果分配给变量。
Before these feature you'd probably write: 在这些功能之前你可能会写:
var car = obj as SomeAuto;
if(car != null)
{
//Do Stuff
}
As pointed out by @BurnBA a difference when using the as
than the original is
is that Note that the as operator performs only reference conversions, nullable conversions, and boxing conversion and therefore cannot be used to check non-nullable value types. 作为使用时所指出的@BurnBA的差
as
比原来的is
的是, 请注意,作为操作者只执行引用转换,可为空的转换,和装箱转换 ,因此不能被用于检查非空值类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.