【问题标题】:The modifier 'static' is not valid for this item / Static interface error in c# [duplicate]修饰符“静态”对此项目无效/c#中的静态接口错误[重复]
【发布时间】:2013-04-12 16:59:19
【问题描述】:

我们如何在接口中实现静态方法...?

public interface ICache
{
  //Get item from cache
  static object Get(string pName);

  //Check an item exist in cache
  static bool Contains(string pName); 

  //Add an item to cache
  static void Add(string pName, object pValue);

  //Remove an item from cache
  static void Remove(string pName);
}

以上界面报错:修饰符'static'对此项无效

【问题讨论】:

  • 使它成为一个普通的接口,并使用类似单例的东西来实现它(不一定是标准的单例)。不要使用静态方法来创建缓存。
  • 不,这些不是同一个问题。在另一个问题中,该人从相同的接口派生,但在派生类中他有一个非静态方法。在这个问题中,我们希望所有派生类都实现一个静态方法。这基本上是一份合同。任何实现 ICache 的东西都有一个静态的 get 方法。我不相信答案。我们可以有这种合同或分类......

标签: c#


【解决方案1】:

你做不到。应该是

   public interface ICache
    {
      //Get item from cache
      object Get(string pName);
      //Check an item exist in cache
      bool Contains(string pName);
      //Add an item to cache
      void Add(string pName, object pValue);
      //Remove an item from cache
      void Remove(string pName);
    }

查看Why Doesn't C# Allow Static Methods to Implement an Interface?

另外Eric Lippert写了一篇很酷的文章系列,叫做

【讨论】:

    【解决方案2】:

    而且绝对正确。您不能在接口中指定静态成员。它必须是:

    public interface ICache
    {
      //Get item from cache
      object Get(string pName);
    
      //Check an item exist in cache
      bool Contains(string pName);
    
      //Add an item to cache
      void Add(string pName, object pValue);
    
      //Remove an item from cache
      void Remove(string pName);
    }
    

    (顺便说一下,您的 cmets 应该是 XML documentation comments - 这会使它们更有用。我在成员之间添加了一些空格以使代码更易于阅读。您还应该考虑使接口通用。)

    您为什么首先尝试让成员静态化?你希望达到什么目标?

    【讨论】:

      【解决方案3】:

      不,您不能...静态方法/变量指的是类本身而不是该类的实例,并且由于接口的目的是由类实现,因此您不能在接口中使用静态方法...没有意义

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-04
        • 2016-11-01
        • 2011-07-30
        • 2021-07-06
        • 1970-01-01
        • 2019-03-13
        • 2011-09-29
        • 1970-01-01
        相关资源
        最近更新 更多