如何使用Dynamic进行回调?

时间:2014-03-17 21:57:52

标签: c# dynamic callback

我一直收到此错误但不确定如何更正

  

错误1无法使用'回拨'作为动态的参数    调度操作,因为它是一个方法组。你有意吗?    调用方法?

    //...
    if (e.Status == LiveConnectSessionStatus.Connected)
    {              
        client = new LiveConnectClient(e.Session);
        LiveOperationResult operationResult = await client.GetAsync("me");
        try
        {

            dynamic meResult = operationResult.Result;

            var openId = meResult.id;
            var email = meResult.emails.preferred;
            //MessageBox.Show(openId);
            //MessageBox.Show(email);
           userService.SignIn(openId, email, Callback);


        }
        catch (LiveConnectException exception)
        {
            MessageBox.Show("Error calling API: " + exception.Message);
        }
    }
}

private void Callback(ErrorModel error)
{
    if (error != null)
    {
        MessageBox.Show(error.FriendlyErrorMsg, error.Caption, MessageBoxButton.OK);
    }
    else
    {

    }
}

public void SignIn(string id, string email, Action<ErrorModel> callBack)
{

}

1 个答案:

答案 0 :(得分:11)

问题在于此调用是动态的:

userService.SignIn(openId, email, Callback);

必须是,因为openIdemail被推断为dynamic类型:

var openId = meResult.id;
var email = meResult.emails.preferred;

您无法在动态调用中使用此类方法组转换 - 这只是使用dynamic的限制之一。

所以,选项:

  • 提供openIdemail个显式类型,如果userService不是dynamic,则会使调用非动态,此方法组转换将起作用。这只是意味着明确指定类型,因为dynamic提供了隐式转换:

    string openId = meResult.id;
    string email = meResult.emails.preferred;
    userService.SignIn(openId, email, Callback);
    
  • 如果您希望Callback调用动态,请从SignIn方法创建特定的委托类型实例:

    var openId = meResult.id;
    var email = meResult.emails.preferred;
    // Or use whichever delegate type is actually appropriate for SignIn
    userService.SignIn(openId, email, new Action<ErrorModel>(Callback));