8,EasyNetQ-多態發佈和訂閱

您能夠訂閱一個接口,而後發佈該接口的實現。spa

咱們來看一個例子。 我有一個接口IAnimal和兩個實現貓和狗:code

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並得到貓和狗類:blog

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

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

讓咱們發佈一隻貓和一隻狗:接口

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使用「發佈」和「訂閱」方法中指定的泛型類型將發佈路由到訂閱。路由

相關文章
相關標籤/搜索