简体   繁体   中英

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

Interface :

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

Static Class:

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();
    }
}

Here, I want to implement both interface methods in the static class method GetArrayLength() .

I don't want to implement interface but I have passed the interface as a parameter in the static class method.

Appreciated any help or guidance.

You cannot implement interface methods without having a derived class. However, you can add derived information to an interface by means of extension methods, if your interface provides enough basic functionality.

For an array, you could have the interface method IndexCheck and derive the array length by checking for the last valid index.

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;
    }
}

Or you could have an array length and derive the index check

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

In both cases, you can later use an IArrayOperation variable with both methods

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

Your derived class instances need to implement the methods that are actually part of the interface, but the extension methods are available without implementation per instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM