簡體   English   中英

將子類傳遞給方法但將超類作為參數?

[英]Passing in a sub-class to a method but having the super class as the parameter?

我有一個抽象類Vehicle其中包含 2 個實現的子類RedVehicleYellowVehicle

在另一個類中,我有一個List<Vehicle>包含兩個子類的實例。 我希望能夠將一個類類型傳遞給一個方法,然后使用該類型來決定我想要對List中的哪一組對象執行某些操作。

由於Class是通用的,我應該用一些東西對其進行參數化,但是將參數作為父類Vehicle停止調用代碼的工作,因為exampleMethod現在需要一種 Vehicle 類型,而不是RedVehicleYellowVehicle的子類。

我覺得應該有一種干凈的方法來做到這一點,那么實現該功能的正確方法是什么?

nb 我不一定必須傳入Class類型,如果有更好的建議,我很樂意嘗試。

調用代碼:

service.exampleMethod(RedVehicle.class);
service.exampleMethod(YellowVehicle.class);

字段/方法:

//List of vehicles
//Vehicle has 2 subclasses, RedVehicle and YellowVehicle
private List<Vehicle> vehicles;

//Having <Vehicle> as the Class parameter stops the calling code working
public void exampleMethod(Class<Vehicle> type) 
{
    for(Vehicle v : vehicles)
    {
        if(v.getClass().equals(type))
        {
            //do something
        }
    }
}

改為這樣做:

public <T extends Vehicle> void exampleMethod(Class<T> type) 

為什么不使用訪問者模式

這樣你

  • 不需要類型標記
  • 讓動態調度處理大小寫區別(而不是if(v.getClass().equals(type))
  • 更靈活(遵循OCP

詳細地:

您的抽象類Vehicle獲得一個方法accept(Visitor v) ,子類通過在v上調用適當的方法來實現它。

public interface Visitor {
  visitRedVehicle(RedVehicle red);
  visitYellowVehicle(YellowVehicle yellow);
}

使用訪問者:

public class Example {

  public void useYellowOnly() {
    exampleMethod(new Visitor() {
        visitRedVehicle(RedVehicle red) {};
        visitYellowVehicle(YellowVehicle yellow) {
             //...action
        });
  }
  public void exampleMethod(Visitor visitor){
      for(Vehicle v : vehicles) {
          v.accept(visitor);
      }  
  }
}

接受的答案有效並讓我到達了我想去的地方。 我想我會添加這個只是為了讓任何可能需要它的人更清楚。

在這種情況下,RevisedExposure 是 Exposure 的子類。 我需要使用其中之一的列表調用 GetMetadata(),這會產生相同的結果集。

private async Task<List<Metadata>> GetMetadata<T>(List<T> exposures) where T : Exposure

現在我可以像這樣從兩個不同版本的列表調用這個方法。

var metadata = await GetExposureMetadata(revisions);

要么

var metadata = await GetExposureMetadata(exposures);

效果很好!

暫無
暫無

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

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