【问题标题】:How can I implement interface methods in the static class without Interface Inheritance in .NET?如何在.NET 中实现没有接口继承的静态类中的接口方法?
【发布时间】:2016-05-11 04:48:57
【问题描述】:

界面:

public interface IArrayOperation
{
    int GetElement(int index);        
    bool IndexCheck(int index);
}

静态类:

public static class TestArray
{
    public static int GetArrayLength(IArrayOperation arrayOperation)
    {
        // Implement your logic here.
        // I need to implement interface method over here.
        throw new NotImplementedException();
    }
}

这里,我想在静态类方法GetArrayLength()中实现这两个接口方法。

我不想实现接口,但是我已经在静态类方法中将接口作为参数传递了。

感谢任何帮助或指导。

【问题讨论】:

  • 谢谢斯图亚特。你是对的。我想通过接口方法获取静态类中的虚拟数组长度。
  • @Stuartd 你为什么重新打开这个问题,它显然是引用的重复?
  • 您必须将实现IArrayOperation 的类的实例传递给GetArrayLength
  • “我想实现这两种接口方法……我不想实现接口”哪个?

标签: c# .net inheritance interface


【解决方案1】:

没有派生类就不能实现接口方法。但是,如果您的接口提供了足够的基本功能,您可以通过扩展方法将派生信息添加到接口。

对于数组,您可以使用接口方法IndexCheck 并通过检查最后一个有效索引来得出数组长度。

public interface IArrayOperation
{       
    bool IndexCheck(int index);
}
public static class TestArray
{
    public static int GetArrayLength(this IArrayOperation arrayOperation)
    {
        int len = 0;
        while (arrayOperation.IndexCheck(len)) { ++len; }
        return len;
    }
}

或者你可以有一个数组长度并派生索引检查

public interface IArrayOperation
{       
    int GetArrayLength();
}
public static class TestArray
{
    public static bool IndexCheck(this IArrayOperation arrayOperation, int index)
    {
        return index >= 0 && index < arrayOperation.GetArrayLength();
    }
}

在这两种情况下,您以后都可以在这两种方法中使用 IArrayOperation 变量

IArrayOperation instance = /* some concrete derived class */;
bool checkResult = instance.IndexCheck(0);
int lengthResult = instance.GetArrayLength();

您的派生类实例需要实现实际上是接口一部分的方法,但扩展方法无需实现每个实例即可使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 2011-02-10
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    相关资源
    最近更新 更多