无效操作异常:委托返回值应可从中分配



我在 Rhino Mock 的 Do 方法上得到了一个例外。

System.InvalidOperationException:委托返回值应为 可从 MediaPlayerImpl.ScreenControl.ScreenCommunicatorState 分配

我不太清楚如何解决它。下面是我的代码。它很容易理解。

var mockCommunicator = Rhino.Mocks.MockRepository.GenerateStrictMock<IScreenCommunicator>();
ManualResetEvent screenTurnedOff = new ManualResetEvent(false);
mockCommunicator.Expect(c => c.TurnScreenOff(default(ScreenCommunicatorState))).IgnoreArguments()
                                .Do(new Action(() => screenTurnedOff.Set()));

  public override ScreenCommunicatorState TurnScreenOn(ScreenCommunicatorState state)
    {
        state = state ?? new ScreenCommunicatorState { isScreenOn = false };
        if (state.isScreenOn)
        {
            // Try and Get the screen power state
            // ....
            Task<byte[]> requestTask = SendRequest(CommandSequences.GetPowerStatus);
            var isPowerOn = InterpretScreenPowerStatusMessage(requestTask);
            if (isPowerOn.Value)
            {
                //        Do nothing
            }
            else if (!isPowerOn.Value)
            {
                SendCommandSequence(CommandSequences.PowerOn);
            }
            else if (isPowerOn == null)
            {
                SendCommandSequence(CommandSequences.PowerOn);
            }


            // NO

        }
        state.isScreenOn = true;
        Task<bool?> screenTurnedOnTask = IsScreenTurnedOn();
        Func<Task<bool?>, Task> doSomeWork = TurnScreenOnAndRectifyScreenInputSource;

        Task<Task> turnScreenOnIfNecessaryTask = screenTurnedOnTask.ContinueWith(doSomeWork, TaskContinuationOptions.NotOnFaulted);
        Task unwrapped = turnScreenOnIfNecessaryTask.Unwrap();
        try
        {
            unwrapped.Wait(); // This will thrown an exception if it's faulted, which is what we want
        }
        catch (AggregateException aggregateException)
        {
            if (aggregateException.InnerExceptions.Count() == 1)
            {
                throw aggregateException.InnerExceptions[0];
            }
            else
            {
                throw;
            }
        }
        return state;
    }

我不得不使用和 Func 代表来解决问题。

.Do(new Func<ScreenCommunicatorState,ScreenCommunicatorState>((id) => {
                                screenTurnedOff.Set();
                                return new ScreenCommunicatorState();
                            }))
                            .Return(new ScreenCommunicatorState());

最新更新