14、Polymorphic Publish and Subscribe 多态发布和订阅

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

让我们看一个示例。我有一个接口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",        //多态订阅,类型参数必须指定
    animal=>
    {
        var cat = animal as Cat;
        var dog = animal 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

posted on 2017-12-05 16:05  困兽斗  阅读(216)  评论(0编辑  收藏  举报

导航