AS 和 IS 的深入比较
Today a question about the is and as operators: is the is operator implemented as a syntactic sugar for the as operator, or is the as operator implemented as a syntactic sugar for the is operator? More briefly, is is as or is as is?
Perhaps some sample code would be more clear. This code
bool b = x is Foo;
could be considered as a syntactic sugar for
bool b = (x as Foo) != null;
in which case is is a syntactic sugar for as. Similarly,
Foo f = x as Foo;
could be considered to be a syntactic sugar for
var temp = x;
Foo f = (temp is Foo) ? (Foo)temp : (Foo)null;
in which case as is a syntactic sugar for is. Clearly we cannot have both of these be sugars because then we have an infinite regress!
The specification is clear on this point; as (in the non-dynamic case) is defined as a syntactic sugar for is.
However, in practice the CLR provides us instruction isinst, which ironically acts like as. Therefore we have an instruction which implements the semantics of as pretty well, from which we can build an implementation of is. In short, de jure is is is, and as is as is is, but de facto is is as and as is isinst.
I now invite you to leave the obvious jokes about President Clinton in the comments.
备注:
as 不是万能转换器
例如:用户自定义转换
1 ClassA{
2
3 public static explicit operator ClassB (ClassA a){
4
5 return new ClassB();
6
7 }
8
9 }
10
11 ClassA a=new ClassA();
12
13 ClassB b;
14
15 b=(ClassA)a;//正确。通过自定义转换
16
17 b=a as ClassB;//返回null。is判断就不会通过
as运算符只执行引用转换和装箱转换。
as运算符无法执行其他转换,如用户定义的转换,这类转换应使用case表达式来代替其执行。
虽说as是is的语法糖,但是is能够用于不可为空类型判断,而as就不能。
"a as int;"这样的代码会错误,除非是“a as int?;”,“ a is int”这样的代码就是没问题的
int a=3;
Console.WriteLine ( a is int );//正常判断,输出true
int? b = a as int?;//正常转换
int c = a as int;//报错:as不能用于不能为null的类型转换
浙公网安备 33010602011771号