您可以订阅接口,然后发布该接口的实现。
我们来看一个例子。我有一个接口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使用发布和订阅方法中指定的泛型类型将发布路由到订阅。