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

  • 相关阅读:
    纪念又一次ak
    hdu5618
    bzoj3393
    bzoj3438
    [JSOI2007]建筑抢修
    [CQOI2014]数三角形
    [BZOJ2662][BeiJing wc2012]冻结
    [NOIP2015]运输计划
    [ZJOI2006]超级麻将
    [APIO2009]抢掠计划
  • 原文地址:https://www.cnblogs.com/wangwust/p/9437447.html
Copyright © 2020-2023  润新知