使用泛型调用重载方法
本文关键字:重载 方法 调用 泛型 | 更新日期: 2023-09-27 18:27:25
我有一个类,它有许多重载方法:
public class CustomerCommandHandlers
{
public void Handler(ChangeNameCommand command)
{
...
}
public void Handler(ChangeAddressCommand command)
{
...
}
}
我已经包括了以下方法:
public void Handle<TCommand>(TCommand command) where TCommand : ICommand
{
Handler((dynamic)command);
}
这允许我从另一个注册命令和命令处理程序的类中调用重载的方法。
但是,当我创建其他commandHandlers(如ProductCommandHandlers、InventoryCommandHandlers等)时,我不希望在每个类中都包含动态方法。
有没有一种方法可以为每个包含此方法的命令处理程序创建一个基类,然后从基类中调用此方法?
感谢
如果您已经在使用动力学,您不妨将其作为基类:
public class Basehandler
{
public void Handle<TCommand>(T command) where TCommand : ICommand {
((dynamic)this).Handler(command);
}
// As fallback if there is no implementation for the command type
public void Handler(ICommand val) {
// You could implement default or error handling here.
Console.WriteLine(val == null ? "null" : val.GetType().ToString());
}
}