如何合并通用类型事件处理程序的附件?

时间:2019-01-19 15:09:57

标签: c# generics events event-handling eventhandler

我有一个动物接口,我有一些实现该接口的类。

public interface IAnimal
{
    int LegCount { get; }
}

public class Dog : IAnimal
{
    public int LegCount { get { return 4; } }
}

public class Octopus : IAnimal
{
    public int LegCount { get { return 8; } }
}

我有一个通用的EventArgs类,该类具有指定类型的动物的实例。

public class AnimalRequiredEventArgs<TAnimal> : EventArgs
    where TAnimal : class, IAnimal
{
    public TAnimal Animal { get; set; }
}

我有一个包含事件的类,该事件需要指定类型的动物的实例。

public class MyClass
{
    public event EventHandler<AnimalRequiredEventArgs<Dog>> DogRequired;
    public event EventHandler<AnimalRequiredEventArgs<Octopus>> OctopusRequired;
}

我有一个带有事件处理程序的类,该事件处理程序将指定类型的动物设置为事件args的通用属性。

public class AnimalsManager
{
    private readonly IList<IAnimal> _animals =
        new List<IAnimal>{new Dog(), new Octopus()};

    public void OnAnimalRequired<TAnimal>(object sender, AnimalRequiredEventArgs<TAnimal> e)
        where TAnimal : class, IAnimal
    {
        e.Animal = _animals.OfType<TAnimal>().FirstOrDefault();
    }
}

如何统一通用类型事件处理程序的附件,如下所示?

public class Program
{
    public static void Main()
    {
        var manager = new AnimalsManager();
        var mine = new MyClass();

        // How can I unite these event handler attachments?
        mine.DogRequired += manager.OnAnimalRequired;
        mine.OctopusRequired += manager.OnAnimalRequired;
    }
}

1 个答案:

答案 0 :(得分:0)

解决此问题的一种方法是创建动物类:

public interface IAnimal
{
    int LegCount { get; }
}

public abstract class Animal: IAnimal
{
     public virtual int LegCount {get{return 4;}}   

     public event EventHandler<AnimalRequiredEventArgs<Animal>> AnimalRequired;

     protected virtual void OnAnimalRequired(AnimalRequiredEventArgs e)
        {
            // Make a temporary copy of the event to avoid possibility of
            // a race condition if the last subscriber unsubscribes
            // immediately after the null check and before the event is raised.
            EventHandler<AnimalRequiredEventArgs<Animal>> handler = AnimalRequired;
            if (handler != null)
            {
                handler(this, e);
            }
        }
}

public class Dog : Animal
{
    public override int LegCount { get { return 4; } }
}

public class Octopus : IAnimal
{
    public override int LegCount { get { return 8; } }
}

然后,您可以根据需要在每个派生类中重写OnAnimalRequired。

对于客户端,将有一个从抽象基类公开的事件。

希望这会有所帮助。