c# - 对不同类型的类实例进行排队

标签 c#

我想将 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/

相关文章:

c# - WCF:使用消息契约创建 Soap header

c# - 如何将 "Add"两个字节放在一起

c# - Caliburn Micro 无法在不同的程序集中找到 View 模型的 View

c# - StyleCop 警告 SA1126 :PrefixCallsCorrectly on name of class

c# - asp.net 上的 HangFire 重复性工作

c# - 安装向导中的数据库连接

c# - Haskell 中的 OOP 样式继承

C# 比较两个字符串的匹配词

c# - 在asp.net中回发后运行Javascript函数

c# - EF 代码优先 : Include not working on optional relationship