Cast vs 'as' operator revisited

后端 未结 5 982
长情又很酷
长情又很酷 2020-12-24 02:33

I know there are several posts already concerning the difference between casts and the as operator. They all mostly restate the same facts:

  • The
5条回答
  •  一个人的身影
    2020-12-24 03:14

    The compiler does not know how to generate code that will work for all cases.

    Consider these two calls:

    MyGenericMethod(new Foo1());
    MyGenericMethod(new Foo2());
    

    now assume that Foo1 contains a cast operator that can convert it to a Bar instance, and that Foo2 descends from Bar instead. Obviously the code involved would depend heavily on the actual T you pass in.

    In your particular case you say that the type is already a Bar type so obviously the compiler can just do a reference conversion, because it knows that is safe, there's no conversion going on or needed.

    Now, the as conversion is more "exploratory", not only does it not consider user conversions, it explicitly allows for the fact that the cast is meaningless, so the compiler let that slide.

提交回复
热议问题