1

这是我想做的一个原型,除了我意识到它不能像我写的那样工作:

using System.Collections.ObjectModel;

namespace Merlinia.CommonClasses
{
   public abstract class JustTesting<TItem> : KeyedCollection<string, TItem>
   {
      protected override string GetKeyForItem(TItem anItem)
      {
         return GetKeyForItem(anItem).ToUpperInvariant();
      }

      protected new abstract string GetKeyForItem(TItem anItem);
   }
}

现在我确实意识到,通过更改派生类中所需的抽象方法的名称,它确实可以工作:

using System.Collections.ObjectModel;

namespace Merlinia.CommonClasses
{
   public abstract class JustTesting<TItem> : KeyedCollection<string, TItem>
   {
      protected override string GetKeyForItem(TItem anItem)
      {
         return NewGetKeyForItem(anItem).ToUpperInvariant();
      }

      protected abstract string NewGetKeyForItem(TItem anItem);
   }
}

只是我希望所有类中的方法名称都相同,GetKeyForItem。有什么办法可以使它工作吗?

4

1 回答 1

2

您可以在层次结构中插入一个额外的类和一个内部辅助函数来执行此操作。

using System.Collections.ObjectModel;

namespace Merlinia.CommonClasses
{
   public abstract class JustTestingBase<TItem> : KeyedCollection<string, TItem>
   {
      internal JustTestingBase()
      {
        // so that other assemblies cannot misuse this as their own base class
      }

      protected sealed override string GetKeyForItem(TItem anItem)
      {
         return GetKeyForItemHelper(anItem).ToUpperInvariant();
      }

      internal abstract string GetKeyForItemHelper(TItem anItem);
   }

   public abstract class JustTesting<TItem> : JustTestingBase<TItem>
   {
      protected new abstract string GetKeyForItem(TItem anItem);

      internal override string GetKeyForItemHelper(TItem anItem)
      {
        return GetKeyForItem(anItem);
      }
   }
}
于 2014-06-19T15:02:48.517 回答