为什么RelayCommand <t> .Execute采用对象而不是T?</t>

时间:2011-06-09 16:48:39

标签: c# silverlight mvvm relaycommand

这没有做任何事情,但导致需要不必要的投射(或者更确切地说,导致我拉下代码库并自己进行更改)。有没有理由这样做?

参考文献:

Source on Codeplex

Blog posting with source

修改 这是一个例子:

DoCommand = new RelayCommand<AsyncCallback>((callBack) =>
{
    Console.WriteLine("In the Action<AsyncCallback>");
    SomeAsyncFunction((async_result) =>
    {
        Console.WriteLine("In the AsyncCallback");
        callBack.Invoke(new MyAsyncResult(true));
    });
});

DoCommand.Execute((iasyncresult) => Console.WriteLine(iasyncresult.IsCompleted));
//Where MyAsyncResult is a class implement IAsyncResult that sets IsCompleted in the constructor
// This will cause the "cannot cast lambda as object" error

2 个答案:

答案 0 :(得分:6)

因为ICommand不是通用的。 ICommand 的通用实现必须从接口转换,处理无效的转换,并将转换实例转发到泛型方法。

答案 1 :(得分:1)

您的错误是由于lambda无法作为object传递。而是尝试:

AsyncCallback callback = (iasyncresult) => Console.WriteLine(iasyncresult.IsCompleted);
DoCommand.Execute(callback);