我想将 2 种类型的类实例放入队列中。 例如如下,
要排队的类)
class A{
int a1;
int a2;
}
class B{
string b1;
string b2;
}
示例1)
ConcurrentQueue<Object> queue = ConcurrentQueue<Object>();
queue.Enqueue(new A());
queue.Enqueue(new B());
Object item;
while (queue.TryDequeue(out item))
{
A a = item as A;
B b = item as B;
if(a != null){
}
else if(b != null){
}
}
示例2)
class AorB{
public A a = null;
public B b = null;
public AorB(A a){ this.a = a; }
public AorB(B b){ this.b = b; }
}
ConcurrentQueue<AorB> queue = new ConcurrentQueue<AorB>();
queue.Enqueue(new AorB(new A()));
queue.Enqueue(new AorB(new B()));
AorB item;
while (queue.TryDequeue(out item))
{
if(item.a != null){
}
else if(item.b != null){
}
}
Sample1、Sample2 还是其他方法哪个更好?
最佳答案
它们实际上都不是一个好的实现。如果(正如您在评论中提到的)它们用于打印或蜂鸣等命令,并且它们的成员不同,那么您应该考虑它们在做什么。解决这个问题的更好方法是将他们正在做的事情提取到一个界面中,例如
public interface ICommand
{
void Execute();
}
然后让 A 和 B 实现 ICommand,以便它们的打印和蜂鸣声由 A 和 B 处理。这样您的调用代码将类似于:
ConcurrentQueue<ICommand> queue = ConcurrentQueue<ICommand>();
queue.Enqueue(new A());
queue.Enqueue(new B());
Object item;
while (queue.TryDequeue(out item))
{
item.execute();
}
这也符合“告诉,不要问”。
关于c# - 对不同类型的类实例进行排队,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17421456/