C# 如果没有.NET中的接口继承,如何在静态类中实现接口方法?
接口:C# 如果没有.NET中的接口继承,如何在静态类中实现接口方法?,c#,.net,inheritance,interface,C#,.net,Inheritance,Interface,接口: public interface IArrayOperation { int GetElement(int index); bool IndexCheck(int index); } 静态类: public static class TestArray { public static int GetArrayLength(IArrayOperation arrayOperation) { // Implement your
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();
}
}
派生类实例需要实现实际上是接口一部分的方法,但是扩展方法不需要每个实例实现即可使用。如果没有派生类,则无法实现接口方法。但是,如果接口提供了足够的基本功能,则可以通过扩展方法向接口添加派生信息 对于数组,可以使用接口方法
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();
}
}
派生类实例需要实现实际上是接口一部分的方法,但是扩展方法不需要每个实例实现即可使用。Thank Stuartd的可能副本。你说得对。我想通过使用接口方法获得静态类中的虚拟数组长度。@Stuartd您为什么重新打开这个问题,它显然是引用的问题的重复?您必须将实现
iarayOperation
的类的实例传递到GetArrayLength
。“我想实现这两种接口方法……我不想实现接口“哪一个?可能是《谢谢斯图亚特》的翻版。你说得对。我想通过使用接口方法获得静态类中的虚拟数组长度。@Stuartd您为什么重新打开这个问题,它显然是引用的问题的重复?您必须将实现iarayOperation
的类的实例传递到GetArrayLength
。“我想实现两种接口方法……我不想实现接口”哪个?