c# – 如何使用Dynamic进行回调?

前端之家收集整理的这篇文章主要介绍了c# – 如何使用Dynamic进行回调?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直收到这个错误,不知道如何纠正它

Error 1 Cannot use ‘Callback’ as an argument to a dynamically
dispatched operation because it is a method group. Did you intend to
invoke the method?

//...
    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)
{

}

解决方法

问题是这个调用是动态的:
userService.SignIn(openId,Callback);

它必须是,因为openId和email被推断为动态类型:

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

您不能在动态调用中使用这样的方法组转换 – 这只是使用动态的限制之一.

所以,选项:

>提供openId和电子邮件显式类型(如果userService不是动态的)将使调用非动态,方法组转换将起作用.这只是意味着明确指定类型,因为动态可以使用隐式转换:

string openId = meResult.id;
string email = meResult.emails.preferred;
userService.SignIn(openId,Callback);

>如果要保持SignIn调用动态,请从Callback方法创建特定的委托类型实例:

var openId = meResult.id;
var email = meResult.emails.preferred;
// Or use whichever delegate type is actually appropriate for SignIn
userService.SignIn(openId,new Action<ErrorModel>(Callback));
原文链接:https://www.f2er.com/csharp/100428.html

猜你在找的C#相关文章