有没有一种方法可以将不同类型的数组传递给接口实现

时间:2020-09-03 03:38:11

标签: c# arrays interface

所以我有以下情况:

我正在编写一个程序,该程序接受各种类型(字符串,字节等)数组中的内容,将该内容解析为数据结构,然后将结构化数据存储在某个位置。由于解析方法可能完全不同,具体取决于接收的数据类型,因此我想定义单独的文件解析类,但定义它们都应实现的方法和属性。我想为此使用一个接口,但是我不知道如何告诉该接口其ParseFile方法例如将接受某种类型的数组作为输入参数。如果我在界面中编写如下内容:

void ParseFile(Array[] fileContents);

然后尝试在ByteParser类中实现该方法,如下所示:

public void ParseFile(Byte[] fileContents){
//Do whatever
}

我收到一个编译器错误,我的实现类未实现ParseFile方法。我认为这是因为编译器默认情况下不进行强制转换,即使ByteArray是Array的派生类,也不是Array类型。

有什么办法可以做我想在这里做的事情,强制接口接受任何类型的数组并允许我的实现类从那里处理它吗?

1 个答案:

答案 0 :(得分:1)

您当前的想法(使用Array Array[])和Byte[]的想法……是不明智的,也不明智的。

例如,.NET要求接口的实现完全匹配,因此,如果您有方法void ParseFile(Array fileContents),则实现也必须拥有void ParseFile(Array fileContents)-您不能拥有ParseFile(Byte[] fileContents)。这就是为什么您不能这样做:

假设它实际上可以编译:

interface IFileBuilder {
    void ParseFile(Array fileContents);
}

class OctetFileBuilder : IFileBuilder {
    public void ParseFile(Byte[] fileContents) {
        // ...
    }
}

...然后运行:

void Main() {
    
    Byte[]   byteArray = new Byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 };
    String[] strArray  = new String[] { "foo", "bar", "baz" };

    OctetFileBuilder ofb = new OctetFileBuilder();
    ofb.ParseFile( byteArray ); // OK, so far so good.

    ofb.ParseFile( strArray ); // Compiler rejects this because `String[]` isn't `Byte[]`. That's also OK.

    IFileBuilder fb = ofb;
    fb.ParseFile( byteArray ); // This would be okay because a `Byte[]` can be the argument for an `Array` parameter.

    fb.ParseFile( strArray ); // But what happens here?
    
}

存在问题的最后一行:fb.ParseFile( strArray )

该实现期望使用Byte[],但是正在传递String[]

我想象您会期望.NET引发运行时错误-或它将以某种方式神奇地知道如何将String[]转换为Byte[](不,不会)。相反,整个程序根本无法编译。

现在,实际上,您的实现必须像这样才能构建:

class OctetFileBuilder : IFileBuilder {
    public void ParseFile(Array fileContents) {
        Byte[] byteArray = (Byte[])fileContents; // Runtime cast.
    }
}

...因此现在您的代码将编译并开始运行,但是在完成之前它会崩溃,因为给ParseFile赋予String[]时,它将导致InvalidCastException,因为您无法从String[]直接投射到Byte[]

解决方案:协变泛型!

这就是通用类型(以及互变和协方差)的全部内容,以及为什么在设计多态接口时需要仔细考虑程序内部数据移动的方向(通常来说) ,“转发” /“输入”数据可以“收缩”,“输出”数据可以“增长” /“扩展” /“扩展”-但反之亦然。in和{ {1}}泛型修饰符用于。

所以我会这样:(免责声明:我不知道您的接口实际上是做什么用的,也不知道为什么您的out方法不希望使用Byte[]之外的任何东西参数...)

ParseFile

(请注意在这种情况下使用逆方差/协方差修饰符(interface IFileBuilder<in TInput> { void ParseFile( IReadOnlyList<TInput> fileContents ) } class OctetFileBuilder : IFileBuilder<Byte> { public void ParseFile(Byte[] fileContents) { // ... } } 部分)是没有意义的,因为.NET中的原始类型和基类型({{1} },in TInputByte等)是没有继承的结构或为密封类型。

用法:

Int32

因此,您的假设运行时错误现在是有保证的编译时错误。

并且编译时错误比运行时错误要好得多,而且这种方法还意味着您可以推断应用程序中数据流的方向。

相关问题