为什么" as"除非在数组中,否则带有类的关键字不起作用?

时间:2016-04-16 17:41:45

标签: c# casting

如果我尝试使用" as"要生成空值的关键字,它会给我运行时错误。

Base x = new AClass() as Base;

但是如果我创建一个数组并实现它就不会发生错误。它给出了我预期的空值。

        I1[] array = new I1[1];
        array[0] = new AClass();

        for (int i = 0; i < array.Length; i++)
        {
            //Works
            Base x = array[0] as Base;

为什么会这样? array [0] = new AClass()。没有数组怎么回事?

1 个答案:

答案 0 :(得分:1)

我认为你的编译错误是:

  

无法转换类型&#39; ConsoleApplication1.AClass&#39;至   &#39; ConsoleApplication1.Base&#39;通过参考转换,拳击   转换,取消装箱转换,包装转换或null类型   转化

AClass未从Base继承时,会发生这种情况。 现在你可能会想到为什么转换到Base的接口也不会失败。这是因为Base的某些子类有可能实现I1,这将是有效的转换。 此外,变量数组与其工作原理或失败原因无关,如下面的代码所示。

我使用了这段代码

        interface I1 { }
        class AClass : I1 { }
        class Base { }
        static void Main(string[] args)
        {
            I1 myAClass = new AClass();
            Base x = myAClass as Base;
        }