[英]Passing in a sub-class to a method but having the super class as the parameter?
我有一个抽象类Vehicle
其中包含 2 个实现的子类RedVehicle
和YellowVehicle
。
在另一个类中,我有一个List<Vehicle>
包含两个子类的实例。 我希望能够将一个类类型传递给一个方法,然后使用该类型来决定我想要对List
中的哪一组对象执行某些操作。
由于Class
是通用的,我应该用一些东西对其进行参数化,但是将参数作为父类Vehicle
停止调用代码的工作,因为exampleMethod
现在需要一种 Vehicle 类型,而不是RedVehicle
或YellowVehicle
的子类。
我觉得应该有一种干净的方法来做到这一点,那么实现该功能的正确方法是什么?
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))
)详细地:
您的抽象类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.