编译通用接口与通用抽象类& params关键字

时间:2015-01-08 15:34:35

标签: c# .net interface compiler-errors abstract-class

考虑以下示例 - 这使用了一个界面:

public interface IAlgorithm<TResult, TInput>
{
    TResult Compute(TInput input);
}

class A : IAlgorithm<int, byte[]>
{
    // Notice the use of params...not strictly what the interface specifies but it works.
    public int Compute(params byte[] input)
    {
        // no sane developer would go to this length to prove a point
        return input[0];
    }
}

A inst = new A();
Console.WriteLine(inst.Compute(1, 2, 3));
// 1

这个例子显示了一个接口,它的方法实现(params byte[])deos与接口契约(byte[])不完全匹配......但是它有效!

考虑以下示例 - 它使用抽象类:

public abstract class Algorithm<TResult, TInput>
{
    public abstract TResult Compute(TInput input);
}

class A : Algorithm<int, byte[]>
{
    // Notice the use of params...not strictly what the abstract class specifies, and it causes the compile to burst into tears!
    public override int Compute(params byte[] input)
    {
        // no sane developer would go to this length to prove a point
        return input[0];
    }
}

A inst = new A();
Console.WriteLine(inst.Compute(1, 2, 3));
//Compiler error: No overload for method 'Compute' takes 3 arguments

我想知道为什么这适用于接口,但不适用于抽象类?

0 个答案:

没有答案
相关问题