"是"操作员表现得有些奇怪

flo*_*ode 4 .net c#

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评估为truefalse),但为什么它应该知道?Intsead为什么不能运行时处理这个?

b)但是如果相反我们处理非引用类型,那么编译器不会抱怨,即使代码是相同的.为什么?

        int i = 100;
        long l;
        if (i is long)
            l = i;
Run Code Online (Sandbox Code Playgroud)

谢谢

Ste*_*ary 6

这与is运营商无关.编译器看到有两个可能的路径,其中只有一个路径将赋值b.

处理值类型时,编译器知道l将隐式初始化为值0.