Operator : is 、as

IS Operator:is 操作符

(1)The phrase “is compatible” means that an object either is of that type or is derived from that type.~短语“兼容”意味着一个对象要么是该类型的,要么是从该类型派生出来的
(2)具体值
int i = 42;
if (i is 42)
{
Console.WriteLine("i has the value 42");
}
(3)为null
object o = null;
if (o is null)
{
Console.WriteLine("o is null");
}
(4)
if (o is Person p)
{
Console.WriteLine($"o is a Person with firstname {p.FirstName}")
}

AS Operator : as操作符

(1)The as operator is used to perform explicit type conversions of reference types.~as 引用类型转换
(2)If the type being converted is compatible with the specified type, conversion is performed successfully.~转换成功
However, if the types are incompatible, the as operator returns the value null.~转换失败
(3)例子:
As shown in the following code, attempting to convert an object reference to a string returns null if the object reference does not actually refer to a string instance.
object o1 = "Some String";
object o2 = 5;
string s1 = o1 as string; // s1 = "Some String" 转换成功
string s2 = o2 as string; // s2 = null 转换失败,不报错,指向null

difference between IS and AS

The as operator allows you to perform a safe type conversion in a single step without the need to first test the type using the is operator and then perform the conversion.
~as 一步
~is 先检查一下,是否可以转换,然后才做事

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • 今天: 1.前桥---返修界面 2.学生毕业预答辩 3.要账---吴,2W 4.6点起床 5.学生生产实习 6.个...
    先胖不算胖阅读 111评论 0 0
  • 彷徨, 无聊的转圈圈, 却舍不得迈出一步。
    慢熟的咖喱阅读 115评论 0 0
  • 今天是2018.10.03,孩子正在参加2018红领巾长征记活动,开始挑战35公里了,这次是第一次在大型活动中当小...
    张河03阅读 3,197评论 0 2
  • 最近在读古典老师的这本《拆掉思维里的墙》,读的很慢很慢,每天大概只能读十几二十页,不是我的阅读速度慢了,是里面的内...
    阿同学阅读 187评论 1 0