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

时间:2020-03-06 14:21:28  来源:igfitidea点击:
class A : IFoo
{
}

...

A[] arrayOfA = new A[10];

if(arrayOfA is IFoo[]) 
{
    // this is not called
}

问题1:为什么arrayOfA不是IFoos的数组?

Q2:为什么我不能将arrayOfA强制转换为IFoo []

解决方案

你可以试试

if (arrayofA[0] is IFoo) {.....}

什么样的答案可以回答问题。 arrayOfA是一个数组。数组是实现ICloneableIListICollectionIEnumerable的对象。 " IFoo"不在其中。

" 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:\>