[英]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()
. 在这里,我想在静态类方法
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. 对于数组,您可以使用接口方法
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;
}
}
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
变量与这两种方法一起使用
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. 您的派生类实例需要实现实际上是接口一部分的方法,但是可以使用扩展方法而无需为每个实例实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.