簡體   English   中英

在.NET中如何在沒有接口繼承的情況下在靜態類中實現接口方法?

[英]How can I implement interface methods in the static class without Interface Inheritance in .NET?

介面

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()實現這兩個接口方法。

我不想實現接口,但是我已經將接口作為參數傳遞給了靜態類方法。

感謝任何幫助或指導。

如果沒有派生類,則無法實現接口方法。 但是,如果接口提供了足夠的基本功能,則可以通過擴展方法將派生的信息添加到接口。

對於數組,您可以使用接口方法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();

您的派生類實例需要實現實際上是接口一部分的方法,但是可以使用擴展方法而無需為每個實例實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM