11-EasyNetQ之多态发布和订阅

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

让我们看下一个示例。我有一个接口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

posted @ 2017-07-09 23:34  Leo  阅读(998)  评论(0编辑  收藏  举报