是否有可能(部分地)实现一个抽象方法,并且仍然需要派生类来实现它?
本文关键字:实现 派生 抽象方法 有可能 是否 一个 | 更新日期: 2023-09-27 18:09:34
这是我想做的一个原型,但我意识到它不能像我写的那样工作:
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。有什么办法能做到吗?
您可以在层次结构中插入一个额外的类和一个内部helper函数来完成此操作。
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);
}
}
}