【问题标题】:Class inherits generic dictionary<string, IFoo> and Interface类继承通用字典<string, IFoo> 和接口
【发布时间】:2008-11-30 11:45:22
【问题描述】:

我有一个继承通用字典和接口的类

public class MyDictionary: Dictionary<string, IFoo>, IMyDictionary
{
}

问题是这个类的消费者正在寻找接口的“.Keys”和“.Values”属性,所以我补充说:

    /// <summary>
    /// 
    /// </summary>
    ICollection<string> Keys { get; }

    /// <summary>
    /// 
    /// </summary>
    IEnumerable<IFoo> Values { get; }

到界面。

现在,实现也需要这个,但是当我实现这些时,我得到了这个错误:

“关键字new是必需的,因为它隐藏了属性Keys ..”

所以我需要做什么。我应该在这些获取属性前添加一个“新”吗?

【问题讨论】:

    标签: c# generics collections interface


    【解决方案1】:

    另一种选择是将界面上的类型更改为:

    public interface IMyDictionary
    {
        /// <summary>
        /// 
        /// </summary>
        Dictionary<string, IFoo>.KeyCollection Keys { get; }
    
        /// <summary>
        /// 
        /// </summary>
        Dictionary<string, IFoo>.ValueCollection Values { get; }
    }
    

    这样接口已经被字典实现了,省去了再次实现属性的麻烦,而且不会隐藏或覆盖原来的实现。

    【讨论】:

    • 我收到此错误:错误 2 可访问性不一致:属性类型 'System.Collections.Generic.Dictionary.KeyCollection' 比属性 'ClassLibrary1.IMyDictionary.Keys' 更难访问
    • 在我的机器上运行良好。确保 IFoo 也是公开的。
    • 还有IMyDictionary界面
    【解决方案2】:

    Dictionary 实现了 IDictionary 接口,该接口已经提供了 Keys 和 Values 属性。不需要创建自己的属性,但绕过编译器警告的方法是在类中属性声明的开头添加 new 关键字。

    【讨论】:

      【解决方案3】:

      原因是您的键和值属性隐藏了 Dictionary 类中键和值属性的实现。

      编辑:是的,您所要做的就是将新关键字添加到您的属性中。所以你的代码看起来像这样:

      class IFoo
      { }
      
      interface MyDictionary
      {
          ICollection<string> Keys { get; }
      
          /// <summary>
          /// 
          /// </summary>
          IEnumerable<IFoo> Values { get; }
      }
      
      class IStuff : Dictionary<string, IFoo>, MyDictionary
      {
          #region MyDictionary Members
      
          //Note the new keyword.
          public new ICollection<string> Keys
          {
              get { throw new NotImplementedException(); }
          }
      
          public new IEnumerable<IFoo> Values
          {
              get { throw new NotImplementedException(); }
          }
      
          #endregion
      }
      

      我仍然建议实施 IDictionary。

      【讨论】:

        【解决方案4】:

        您也可以使用显式接口实现。这样,如果有人通过使用接口 IMyDictionary 来引用 MyDictionary,他们将看到方法,而没有其他任何东西。我还建议改为实施 IDictionary。除非您想将使用限制为键和值。

        public class MyDictionary : Dictionary<string, IFoo>, IMyDictionary
        {
            ICollection<string> IMyDictionary.Keys
            {
                get { return Keys; }
            }
        
            IEnumerable<IFoo> IMyDictionary.Values
            {
                get { return Values; }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2022-01-25
          • 2013-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-05
          • 1970-01-01
          • 2015-10-03
          • 2014-12-24
          相关资源
          最近更新 更多