1)根据我的书,is操作员可以检查只有在引用转换,装箱或拆箱时,是否可以将expression E(E is type)转换为目标类型E.由于在以下示例is中未检查三种类型的转换中的任何一种,因此代码不起作用,但它确实:
long l; // EDIT - I forgot to add this line of code in my initial post
int i=100;
if (i is long) //EDIT - in my initial post I've claimed condition returns true, but it really returns false
l = i;
Run Code Online (Sandbox Code Playgroud)
2)
一个)
B b;
A a = new A();
if (a is B)
b = (B)a;
int i = b.l;
class A { public int l = 100; }
class B:A { }
Run Code Online (Sandbox Code Playgroud)
上面的代码总是会导致编译时错误“Use of unassigned variable”.如果条件a is B求值为false,则b不会赋值,但如果条件为true,则它将.因此,通过允许这样的代码编译器无法知道语句b后面的代码的使用是否if有效(由于不知道是否a is b评估为true或false),但为什么它应该知道?Intsead为什么不能运行时处理这个?
b)但是如果相反我们处理非引用类型,那么编译器不会抱怨,即使代码是相同的.为什么?
int i = 100;
long l;
if (i is long)
l = i;
Run Code Online (Sandbox Code Playgroud)
谢谢
| 归档时间: |
|
| 查看次数: |
187 次 |
| 最近记录: |