【问题标题】:C# Interfaces with static methods [duplicate]具有静态方法的 C# 接口 [重复]
【发布时间】:2017-12-04 23:09:07
【问题描述】:

这是我的界面:

interface IComandos<T>
{
    void Inserir();
    IList<T> Pesquisar(string termo);
    void Editar();
    void Excluir();
}

这里是一个实现接口的类:

 class Partido : IComandos<Partido>
        {
            public string Nome { get; set; }
            public string Sigla { get; set; }
        ...

    public IList<Partido> Pesquisar(string termo)
        {
            throw new NotImplementedException();
        }

问题:我需要我的“Pesquisar”方法是静态的。我该怎么做?我真的需要我的方法像这样工作 -> Partido.Pesquisar("something");

【问题讨论】:

  • “我需要我的“Pesquisar”方法是静态的” 为什么(你这么认为)?
  • 好吧,如果你真的需要一个静态方法,定义一个静态方法。问题是什么? Partido 是一个类,你可以为一个类定义静态方法

标签: c#


【解决方案1】:

来自 MSDN Interfaces (C# Programming Guide):

接口不能包含常量、字段、运算符、实例 构造函数、析构函数或类型。 不能包含静态成员。 接口成员自动公开,不能包含 任何访问修饰符。

所以答案是:不,你不能在接口中定义静态成员。

【讨论】:

  • 从 C# 8.0 开始,您可以在接口中使用静态方法和字段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
  • 2018-05-05
  • 2013-05-24
相关资源
最近更新 更多