EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

OR

C#AS操作符、IS操作符和模式变量

AS操作符

 

as操作符会执行向下转换,如果转换失败,不会抛出异常,值会变为null。

 

什么是向下转换→C#引用转换

Asset a=new Asset();
Stock s=a as Stock;       // s is null ; no exception thrown

 

as操作符无法做自定义转换

long x=3 as long;  //Compile-time error

 

IS操作符

 

✦ is操作符会检验引用的转换是否成功。换句话说,判断对象是否派生于某个类(或者实现了某个接口)

✦ 通常用于向下转换前的验证:

if(a is Stock)
     Console.WriteLine(((Stock)a).SharesOwned);

✦ 如果拆箱转换可以成功的话,那么is操作符的结果会是true。

 

a is Stock 用来判定 a 是否派生于Stock 或者说a是不是Stock本身。

a is IStock 用来判定a是否实现了接口。

 

这么一来,其实就能说明为什么要有IS操作符。

is操作符可以帮助协同工作的人,认清楚实例对象,严谨地写代码,防止报错。

 

模式变量

 

C# 7.0里面,在使用is操作符的时候,可以引入一个变量。

if(a is Stock s)
     Console.WriteLine(s.SharesOwned);

等同于

Stock s;
if(a is Stock)
{
    s=(Stock) a;
    Console.WriteLine(s.ShareOwned);
}

 

引入的 变量可以立即“消费”

if (a is Stock s&&s.ShareOwned>100000)
    Console.WriteLine("Wealthy");

出了if else 依旧可以使用:

if(a is Stock s&&s.SharesOwned>100000)
    Console.WriteLine("Wealthy");
else
    s=new Stock();   //s is in scope

Console.WriteLine(s.SharesOwned);   // Still in scope

 

This article was last edited at 2020-03-12 14:09:48

* *