【发布时间】:2016-06-01 22:42:31
【问题描述】:
我要创建很多类,比如
public static class M2SA
{
// Median of 2 sorted arrays
public static int Method ( int[] A, int[] B )
{
int m = A.Length, n = B.Length;
if((m | n) == 0)
throw new ArgumentException("A and B cannot both be empty");
int i = 0, j = 0, k = (m + n)/2;
while((i + j) < k)
{
if(i == m) ++j;
else if(j == n || A[i] <= B[j]) ++i;
else ++j;
}
if(i == m) return B[j];
else if(j == n) return A[i];
else return Math.Min(A[i],B[j]);
}
public static int Alternative ( int[] A, int[] B )
{
if ((A.Length | B.Length) == 0)
throw new ArgumentException("A and B cannot both be empty");
int[] mergedAndSorted = A.Concat(B).OrderBy(x => x).ToArray();
return mergedAndSorted[mergedAndSorted.Length / 2];
}
public static bool Test ()
{
return false;//Placeholder - haven't implemented yet
}
}
因为他们都会实施
- 一个名为
Method的public static方法 - 一个名为
Alternative的public static方法与Method具有相同的签名 - 一种方法
public static bool Test,用于测试Method和Alternative是否为给定的一组生成的输入产生等效的输出。
这些类可能有其他方法作为助手。
有没有一种方法可以创建一个足够通用的接口,它需要上述内容,但除此之外一无所知?还是要求其方法具有某些签名?
例如,我可能有另一个类,如
public static class UnstablePartition
{
public static void intswap(ref int a, ref int b)
{
// I'm amazed that there isn't already a method for this in the .NET library (???)
int temp = a;
a = b;
b = temp;
}
public delegate bool UnaryPredicate (int i);
public static void Method ( int[] arr, UnaryPredicate pred )
{
for(int i = 0, j = arr.Length; i < j; )
{
if (!pred(arr[i])) ++i;
else if (pred(arr[j])) --j;
else intswap(ref arr[i],ref arr[j]);
}
}
public static void Alternative(int[] arr, UnaryPredicate pred)
{
int[] partioned = new int[arr.Length];
for (int ai = 0, pi = 0, pj = partioned.Length; ai < arr.Length; ++ai)
{
if (pred(arr[ai])) partioned[pj--] = arr[ai];
else partioned[pi++] = arr[ai];
}
Array.Copy(partioned, arr, partioned.Length);
}
public static bool Test()
{
return false;//Placeholder - haven't implemented yet
}
}
所以我想要一个类似的界面(我知道下面是完全无效...)
public static interface InterviewQuestion
{
public static Method;
public static Alternative;
public static bool Test();
}
然后我会像这样实现它
public static class M2SA : InterviewQuestion
【问题讨论】:
-
是否可以使用静态成员创建静态接口?...不。
-
接口不能是
static也不能是它的成员 -
“静态界面”的意义何在?没有静态继承——如果你调用一个静态方法,你就是在指定你的意思是哪个类。解决这个问题的方法是让你的类是非静态的。
-
即使可以在接口中定义静态方法......如果它们有不同的签名又有什么意义呢?编译器如何知道这些静态方法需要哪些参数?
标签: c# .net oop inheritance