泛型类隐式T

时间:2014-06-23 12:44:31

标签: c# generics

我有ICommand类型的通用命令:

class SimpleCommand<T> : ICommand
{
    public SimpleCommand(Action<T> execute, Predicate<T> canExecute = null)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }
    /*
        All the other stuff...
    */
}

像这样使用:

ICommand command = new SimpleCommand<string>(MyMethod);

private void MyMethod(string arg) { ... }

使用时,我希望编译器自动从传递的Action中获取T,所以我可以像tihs一样写:

ICommand command = new SimpleCommand(MyMethod);

但是,如果我这样写,我会收到编译器错误。是否可以让编译器从Method参数类型中获取T类?

2 个答案:

答案 0 :(得分:2)

您可以实施静态Create方法。

public static class Command
{
    public static SimpleCommand<T> Create<T>(Action<T> execute, Predicate<T> canExecute = null)
    {
        return new SimpleCommand<T>(execute, canExecute);
    }
}

这应该允许编译器在调用时选择泛型参数:

ICommand command = Command.Create(MyMethod);

答案 1 :(得分:2)

不是构造函数,但是你可以实现工厂模式,它可以根据参数实例化正确的类型

相关问题