为什么接口不能指定静态方法? [英] Why can't interfaces specify static methods?

查看:19
本文介绍了为什么接口不能指定静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经被问过一遍又一遍,但我似乎找不到足够好的答案.因此,为了弄清楚我想知道什么,我将把它分成两个问题:

I know this question has been asked over and over, but I can't seem to find good enough answers. So to make it clear what I'm trying to know, I'll split this in two questions:

  1. 为什么接口不能有静态方法签名?我将尝试抢占非答案,询问为什么我想通过以下方式执行此操作:我希望能够在 SqliteCodeGenerator<上静态调用 GetDbConnectionType()/code> 和 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";
    }
}

  • 另一方面,这是第二个问题的问题,如果您知道实现上述目标的好方法,那么无论如何...

  • On the other hand, and this is the matter of this second question, if you know of a good alternative to reach the aforementioned goal, then by all means...

    推荐答案

    假设你可以在一个接口中指定一个类型必须有一个特定的静态方法......你会如何称呼它?多态通过实例起作用 - 而静态成员显式使用实例.

    Suppose you could specify in an interface that a type had to have a particular static method... how would you call it? Polymorphism works through instances - whereas static members explicitly don't use instances.

    现在,话虽如此,在一种情况下,我可以看到静态接口成员在工作:泛型类型.例如:

    Now, having said that, there's one situation in which I can see static interface members working: generic types. For example:

    // This isn't valid code...
    public void Foo<T>() where T : ICodeGenerator
    {
        string type = T.GetDbConnectionType();
    }
    

    这将调用 concrete 类型 T 上的静态成员.

    That would call the static member on the concrete type T.

    我已经写了更多关于这个的博客,但我怀疑好处并不能证明复杂性是合理的.

    I've blogged more about this, but I suspect the benefit doesn't justify the complexity.

    就替代方案而言 - 通常您会有另一个接口,并且有单独的类型来实现该接口.这在某些情况下很有效,但在其他情况下则不然.

    In terms of alternatives - usually you'd have another interface, and have separate types to implement that interface. That works well in some contexts, but not in others.

    这篇关于为什么接口不能指定静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆