C#VS2010
我的基类中有2个方法。一个是带有空参数列表的虚拟,另一个是非虚拟的重载,但允许传入几个参数。
在一些派生类中重写了空虚方法,以调用重载的基本函数。
重载的方法使得传递的值变为需要调用虚方法的基本版本。
我该怎么做? (为了解决这个问题,我将代码从虚方法中移到了一个单独的私有方法中,这两个方法都调用了这个方法,但我想知道是否需要这样做)
using KVP = KeyValuePair<string, object>;
abstract class BaseRecordClass
{
private IEnumerable<KVP> BasePrep()
{
// Serialization can't handle DbNull.Value so change it to null
var result = Data.Select(kvp => new KVP(kvp.Key, kvp.Value == DBNull.Value ? null : kvp.Value)).ToList();
// Add the table name
result.Add(new KVP(TableNameGuid, TableName));
return result;
}
/// <summary>
/// Prepares class for sending/serializing over the web.
/// </summary>
/// <returns></returns>
public virtual IEnumerable<KVP> PrepareForWebInterface()
{
return BasePrep();
}
/// <summary>
/// Override to the above that adds extra items to
/// result eg lists of subrecords
/// </summary>
/// <param name="items"></param>
/// <returns></returns>
protected IEnumerable<KVP> PrepareForWebInterface(params KVP[] items)
{
var result = BasePrep().ToList();
result.AddRange(items);
return result;
}
}// class
class SubRecordClass
{
public override IEnumerable<KVP> PrepareForWebInterface()
{
var parms = new List<KVP>
{
new KVP(CustomGroupsFieldListStr, _customGroupsFieldList.Select(item => item.PrepareForWebInterface()).ToList()),
new KVP(UserGroupsListStr, _userGroupsList.Select(item => item.PrepareForWebInterface()).ToList()),
new KVP(StaffPermissionsStr, _staffPermissions.Select(item => item.PrepareForWebInterface()).ToList())
};
return PrepareForWebInterface(parms.ToArray());
}
}
答案 0 :(得分:1)
从你的问题中你不清楚你想要什么。
听起来你想调用一个在子类中重写的基本方法,从同一个类中的继承方法调用,这个方法没有被覆盖 - 这有意义吗?
如果是这样,我相信您只需要使用base.YourMethod()
在基类中调用该方法。
为了简单和清晰起见,您可能最好只是将相关逻辑保存在一个单独的方法中,就像您目前所做的那样。基于你的稀疏描述,我真的没有看到任何错误。