• 8,EasyNetQ-多态发布和订阅


    您可以订阅一个接口,然后发布该接口的实现。

    我们来看一个例子。 我有一个接口IAnimal和两个实现猫和狗:

    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并获得猫和狗类:

    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使用“发布”和“订阅”方法中指定的泛型类型将发布路由到订阅。

  • 相关阅读:
    Queries about less or equal elements CodeForces
    Session in BSU CodeForces
    基环树
    骑士 HYSBZ
    Valid BFS? CodeForces
    Trips CodeForces
    The writing on the wall 南京网络赛2018B题
    Building a Space Station
    Constructing Roads
    Networking
  • 原文地址:https://www.cnblogs.com/zd1994/p/8650968.html
Copyright © 2020-2023  润新知