这是我想要做的原型,除了我意识到它不能像我写的那样工作:
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。有没有办法让这项工作?
答案 0 :(得分: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);
}
}
}