我知道这个问题已经被问了一遍又一遍,但我似乎找不到足够好的答案。因此,为了弄清楚我想知道的是什么,我将把它分成两个问题:
为什么接口(interface)不能有静态方法签名?我将尝试先发制人,问为什么我要用以下方法来解决这个问题:我希望能够静态调用
GetDbConnectionType()
在SqliteCodeGenerator
和MssqlCodeGenerator
:interface ICodeGenerator { // this is the method I would like to be static: string GetDbConnectionType(); } abstract class CodeGeneratorBase : ICodeGenerator { public abstract string GetDbConnectionType(); public void GenerateSomeCode(StringBuilder s) { s.AppendLine("var foo = new " + GetDbConnectionType() + "();"); } } class SqliteCodeGenerator : CodeGeneratorBase { public override string GetDbConnectionType() { return "SQLiteConnection"; } } class MssqlCodeGenerator : CodeGeneratorBase { public override string GetDbConnectionType() { return "SqlConnection"; } }
另一方面,这是第二个问题的问题,如果您知道实现上述目标的一个很好的替代方案,那么无论如何...
最佳答案
假设您可以在一个接口(interface)中指定一个类型必须有一个特定的静态方法...您将如何调用它?多态性通过实例 起作用 - 而静态成员明确不使用实例。
现在,话虽如此,在一种情况下我可以看到静态接口(interface)成员在工作:泛型类型。例如:
// This isn't valid code...
public void Foo<T>() where T : ICodeGenerator
{
string type = T.GetDbConnectionType();
}
这将调用 具体 类型 T
上的静态成员。
我已经 blogged more about this ,但我怀疑好处并不能证明其复杂性。
就备选方案而言——通常您会有另一个接口(interface),并且有单独的类型来实现该接口(interface)。这在某些情况下效果很好,但在其他情况下效果不佳。
关于c# - 为什么接口(interface)不能指定静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10837906/