如何使用反射从子类调用父类中的方法?

时间:2019-06-23 14:21:40

标签: c#

我创建子对象(客户,产品等),并在父类(AggregateRoot)中调用方法ApplyChange,从该方法中,我想在子类中为通过的事件调用方法Apply。可以使用反射还是我应该改变一些东西?

public abstract class AggregateRoot
{
    public void ApplyChange(IEvent @event)
    {
        Apply(@event); // how to call this method?
    }
}


public class Customer : AggregateRoot
{    
    private void Apply(CustomerCreatedEvent e)
    {
        Console.WriteLine("CustomerCreatedEvent");
    }
}

public class Product : AggregateRoot
{
    private void Apply(ProductCreatedEvent e)
    {
        Console.WriteLine("ProductCreatedEvent");
    }
}

public interface IEvent
{
}

public class CustomerCreatedEvent : IEvent
{
}

public class ProductCreatedEvent : IEvent
{
}

class Program
{
    static void Main(string[] args)
    {
        Customer customer = new Customer();
        customer.ApplyChange(new CustomerCreatedEvent());

        Product product = new Product();
        product.ApplyChange(new ProductCreatedEvent());
    }
}

1 个答案:

答案 0 :(得分:3)

  

是否可以使用反射或我应该更改某些东西?

我现在专注于不反射,因为IMO反射应该是这里的最后手段。

选项1:抽象方法

您可以将Apply设为抽象方法,然后可以从AggregateRoot进行调用。

例如

using System;


public abstract class AggregateRoot
{
    public void ApplyChange(IEvent @event)
    {
        Apply(@event); // how to call this method?
    }

    protected abstract void Apply(IEvent e);
}

public class Customer : AggregateRoot
{
    protected override void Apply(IEvent e)
    {
        if (e is CustomerCreatedEvent)
        {
            Console.WriteLine("CustomerCreatedEvent");
        }
    }
}

public class Product : AggregateRoot
{
    protected override void Apply(IEvent e)
    {
        if (e is ProductCreatedEvent)
        {
            Console.WriteLine("ProductCreatedEvent");
        }
    }
}

public interface IEvent
{
}

public class CustomerCreatedEvent : IEvent
{
}

public class ProductCreatedEvent : IEvent
{
}

但是请注意,它具有以下缺点:

  • 方法需要非私有
  • 应具有与Apply相同的参数类型。 (IEvent参数)-因此,我在Apply方法中添加了类型检查。

选项2:抽象方法和通用AggregateRoot

另一种选择是使AggregateRoot对IEvent类型通用,例如像这样的东西。

using System;


public abstract class AggregateRoot<TEvent>
where TEvent : IEvent
{
    public void ApplyChange(TEvent @event)
    {
        Apply(@event); // how to call this method?
    }

    protected abstract void Apply(TEvent e);
}

public class Customer : AggregateRoot<CustomerCreatedEvent>
{
    protected override void Apply(CustomerCreatedEvent e)
    {
        Console.WriteLine("CustomerCreatedEvent");

    }
}

public class Product : AggregateRoot<ProductCreatedEvent>
{
    protected override void Apply(ProductCreatedEvent e)
    {
        Console.WriteLine("ProductCreatedEvent");
    }

}

public interface IEvent
{
}

public class CustomerCreatedEvent : IEvent
{
}

public class ProductCreatedEvent : IEvent
{
}

请注意,在这种情况下,我还更改了ApplyChange。

如果这些方法不能解决您的问题,请详细说明您要归档的内容,否则将是XY problem