在C#中将对象数组(实现接口IFoo)转换为IFoo []

Chr*_*ris 1 c#

class A : IFoo
{
}

...

A[] arrayOfA = new A[10];

if(arrayOfA is IFoo[]) 
{
    // this is not called
}
Run Code Online (Sandbox Code Playgroud)

Q1:为什么arrayOfA不是一个阵列IFoos

Q2:为什么我不能投arrayOfAIFoo[]

Ed *_*ess 6

arrayOfA IFoo[].

你的程序肯定有其他问题.

您似乎已经模拟了一些代码来显示问题,但事实上您的代码(见下文)可以按预期工作.尝试使用真实代码更新此问题 - 或尽可能接近真实 - 我们可以再看看.

using System;
public class oink {
    public static void Main() {
        A[] aOa = new A[10];

        if (aOa is IFoo[]) { Console.WriteLine("aOa is IFoo[]"); }

    }
    public interface IFoo {}
    public class A : IFoo {}
}

PS D:\> csc test.cs
Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.1
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.

PS D:\> D:\test.exe
aOa is IFoo[]
PS D:\>
Run Code Online (Sandbox Code Playgroud)