你能够订阅一个接口,然后发布基于这个接口的实现。

让我们看下一个示例。我有一个接口IAnimal和两个实现Cat和Dog:

public interface IAnimal
{
    string Name { get; set; }
}

public class Cat : IAnimal
{
    public string Name { get; set; }
    public string Meow { get; set; }
}

public class Dog : IAnimal
{
    public string Name { get; set; }
    public string Bark { get; set; }
}

我能够订阅IAnimal接口,并接收Cat和Dog这个两个类:

bus.Subscribe<IAnimal>("polymorphic_test",
    @interface =>
    {
        var cat = @interface as Cat;
        var dog = @interface as Dog;

        if (cat != null)
        {
            Console.WriteLine("Name = {0}", cat.Name);
            Console.WriteLine("Meow = {0}", cat.Meow);
        }
        else if (dog != null)
        {
            Console.WriteLine("Name = {0}", dog.Name);
            Console.WriteLine("Bark = {0}", dog.Bark);
        }
        else
        {
            Console.WriteLine("message was not a
                dog or a cat");
        }
    }
);

让我们发布Cat和Dog:

var cat = new Cat
{
    Name = "Gobbolino",
    Meow = "Purr"
};

var dog = new Dog
{
    Name = "Rover",
    Bark = "Woof"
};

bus.Publish<IAnimal>(cat);
bus.Publish<IAnimal>(dog);

注意:必须显示的指定发布了IAnimal接口。EasyNetQ在发布和订阅方法中指定了泛型去发布和订阅。

英文地址:https://github.com/EasyNetQ/EasyNetQ/wiki/Polymorphic-Publish-and-Subscribe
本文地址:http://www.cnblogs.com/HuangLiang/p/EasyNetQ_Polymorphic_Publish_and_Subscribe.html

相关文章:

  • 2021-11-01
  • 2022-12-23
  • 2021-07-06
  • 2021-10-31
  • 2022-01-20
  • 2022-12-23
  • 2022-02-20
猜你喜欢
  • 2021-08-27
  • 2021-10-16
  • 2021-11-10
  • 2021-11-01
  • 2021-07-21
  • 2022-12-23
  • 2021-09-11
相关资源
相似解决方案