c# - 使用泛型调用重载方法

标签 c# generics dynamic

我有一个类,其中有许多重载方法:

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/

相关文章:

c# - 窗体 : scroll programmatically

c# - 调用线程必须是 STA,因为在 WPF 中很多 UI 组件都需要这个

c# - 将 List<T> 转换为包含另一个 List<T> 的另一个 List<T>

c# - 这个图案有名字吗

html - YouTube 嵌入动态大小与最小和最大大小

angularjs - 根据 $scope 值在 View 中加载 Angular 指令

c# - XAML 上的 Xamarin Forms ListView ItemTapped/ItemSelected 命令绑定(bind)

c# - Linq 查询 - 创建通用子集

java - 避免在 Java 中未经检查的嵌套映射转换

基于语言或CultureInfo的C#动态对象实例化