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 先检查一下,是否可以转换,然后才做事
网友评论