我有一个类,其中有许多重载方法:
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);
}
它允许我从注册命令和命令处理程序的另一个类调用重载方法。
但是,当我创建其他命令处理程序(例如 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());
}
}
关于c# - 使用泛型调用重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9632015/