簡體   English   中英

如何在不調用重寫的情況下從基類中的另一個方法調用基虛方法?

[英]How do I call a base virtual method from another method in the base class without calling the overrides?

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());
  }      
}

從您的問題中不清楚您想要的是什么。

聽起來好像您想從同一類的繼承方法中調用子類中被重寫的基類方法,而該基類方法不會被重寫-這有意義嗎?

如果是這樣,我相信您只需要使用base.YourMethod()在基類中調用該方法。

但是,為了簡化和清楚起見,最好像現在這樣,最好將相關邏輯保存在單獨的方法中。 根據您的稀疏描述,我真的看不出有什么問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM