问题描述
我有多个定义不同对象的类(例如苹果、香蕉、柠檬),以及转换这些对象的多个处理器(例如苹果处理器、香蕉处理器、柠檬处理器)。
我想要一个函数,它有一个对象和一个处理器作为输入,并在给定对象的处理器中启动一个函数。
像这样的事情,显然它不起作用,因为没有为类型 Object 定义 process 函数。
private void doStuff (Object item,Object processor){
processor.process(item);
}
除了为每个处理器-项目对编写一个函数之外,还有什么更好的方法可以做到这一点?
解决方法
一种方法是使用泛型
为您的项目(即 Fruit)创建一个超类并使这些项目扩展该类,然后编辑 Processor 类以接受泛型:
doc.LoadHtml("<table><thead><th>Hora</th><th>Estado</th><th>Motivo</th><th>Local</th><th>Recetor</th></thead></table>");
var nodes = doc.DocumentNode.SelectNodes("//thead").ToList();
foreach (var node in nodes) {
node.Remove();
}
txtResults.Text=doc.Text;
通过这种方式,您只需实例化所需类型的新处理器(即 public class Processor<T extends Fruit>{
public void process(T item){
//do your stuff here,may be check if item is instance of any fruit you need
}
}
)并调用 new Processor<Apple>
方法。