我创建子对象(客户,产品等),并在父类(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());
}
}
答案 0 :(得分:3)
是否可以使用反射或我应该更改某些东西?
我现在专注于不反射,因为IMO反射应该是这里的最后手段。
您可以将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
{
}
但是请注意,它具有以下缺点:
IEvent
参数)-因此,我在Apply方法中添加了类型检查。另一种选择是使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