c# - 将 C# PageAsyncTask() 转换为 VB.Net 等效项时出现问题

标签 c# vb.net async-await delegates c#-to-vb.net

尝试将 C# 函数转换为 VB.Net 等效函数时出现编译错误。 C# 中的 PageAsyncTask 需要任务输入,但在 VB.Net 中它正在寻找 Func(Of Task)。我能找到的所有在线转换器都无法正确翻译该语言。 错误是: “任务”类型的值无法转换为“Func(Of Task)”

不确定如何进行(我猜我需要定义一个事件?)。 这是原始的 C# 代码

        protected void Page_Load(object sender, EventArgs e)
    {
        {
            AsyncMode = true;
            if (!dictionary.ContainsKey("accessToken"))
            {
                if (Request.QueryString.Count > 0)
                {
                    var response = new AuthorizeResponse(Request.QueryString.ToString());
                    if (response.State != null)
                    {
                        if (oauthClient.CSRFToken == response.State)
                        {
                            if (response.RealmId != null)
                            {
                                if (!dictionary.ContainsKey("realmId"))
                                {
                                    dictionary.Add("realmId", response.RealmId);
                                }
                            }

                            if (response.Code != null)
                            {
                                authCode = response.Code;
                                output("Authorization code obtained.");
                                PageAsyncTask t = new PageAsyncTask(performCodeExchange);
                                Page.RegisterAsyncTask(t);
                                Page.ExecuteRegisteredAsyncTasks();
                            }
                        }
                        else
                        {
                            output("Invalid State");
                            dictionary.Clear();
                        }
                    }
                }
            }
            else
            {
                homeButtons.Visible = false;
                connected.Visible = true;
            }
        }
    }

以及代码转换成什么:

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If True Then
            AsyncMode = True
            If Not dictionary.ContainsKey("accessToken") Then
                If Request.QueryString.Count > 0 Then
                    Dim response = New AuthorizeResponse(Request.QueryString.ToString())
                    If response.State IsNot Nothing Then
                        If oauthClient.CSRFToken = response.State Then
                            If response.RealmId IsNot Nothing Then
                                If Not dictionary.ContainsKey("realmId") Then
                                    dictionary.Add("realmId", response.RealmId)
                                End If
                            End If

                            If response.Code IsNot Nothing Then
                                authCode = response.Code
                                output("Authorization code obtained.")
                                Dim t As New PageAsyncTask(performCodeExchange)
                                Page.RegisterAsyncTask(t)
                                Page.ExecuteRegisteredAsyncTasks()
                            End If
                        Else
                            output("Invalid State")
                            dictionary.Clear()
                        End If
                    End If
                End If
            Else
                homeButtons.Visible = False
                connected.Visible = True
            End If
        End If
    End Sub

问题区域:

Dim t As New PageAsyncTask(performCodeExchange)

任务函数是返回任务的 performCodeExchange

    Public Async Function performCodeExchange() As Task
    output("Exchanging code for tokens.")
    Try
        Dim tokenResp = Await oauthClient.GetBearerTokenAsync(authCode)
        If Not _dictionary.ContainsKey("accessToken") Then
            _dictionary.Add("accessToken", tokenResp.AccessToken)
        Else
            _dictionary("accessToken") = tokenResp.AccessToken
        End If

        If Not _dictionary.ContainsKey("refreshToken") Then
            _dictionary.Add("refreshToken", tokenResp.RefreshToken)
        Else
            _dictionary("refreshToken") = tokenResp.RefreshToken
        End If

        If tokenResp.IdentityToken IsNot Nothing Then
            idToken = tokenResp.IdentityToken
        End If
        If Request.Url.Query = "" Then
            Response.Redirect(Request.RawUrl)
        Else
            Response.Redirect(Request.RawUrl.Replace(Request.Url.Query, ""))
        End If
    Catch ex As Exception
        output("Problem while getting bearer tokens.")
    End Try
End Function

为了完整起见,原始的 C# 代码:

       public async Task performCodeExchange()
    {
        output("Exchanging code for tokens.");
        try
        {
            var tokenResp = await oauthClient.GetBearerTokenAsync(authCode);
            if (!dictionary.ContainsKey("accessToken"))
                dictionary.Add("accessToken", tokenResp.AccessToken);
            else
                dictionary["accessToken"] = tokenResp.AccessToken;

            if (!dictionary.ContainsKey("refreshToken"))
                dictionary.Add("refreshToken", tokenResp.RefreshToken);
            else
                dictionary["refreshToken"] = tokenResp.RefreshToken;

            if (tokenResp.IdentityToken != null)
                idToken = tokenResp.IdentityToken;
            if (Request.Url.Query == "")
            {
                Response.Redirect(Request.RawUrl);
            }
            else
            {
                Response.Redirect(Request.RawUrl.Replace(Request.Url.Query, ""));
            }
        }
        catch (Exception ex)
        {
            output("Problem while getting bearer tokens.");
        }
    }

我不确定在这里做什么 - 传递委托(delegate)?如何通过任务完成(在 VB.Net 中)?

最佳答案

在 C# 中执行 PageAsyncTask t = new PageAsyncTask(performCodeExchange); 时,会隐式创建一个指向 performCodeExchange 方法的委托(delegate),并将其传递给 的构造函数PageAsyncTask.

现在 VB 中的语句 Dim t As New PageAsyncTask(performCodeExchange) 略有不同。 VB 中的函数可以在没有括号的情况下进行计算,因此这等效于 Dim t As New PageAsyncTask(performCodeExchange())。这意味着 PageAsyncTask 的构造函数接收 performCodeExchange 的评估结果,而不是该方法的委托(delegate)。

要在 VB 中获得委托(delegate),可以使用 AdressOf 关键字。代码应重写为:

Dim t As New PageAsyncTask(AddressOf performCodeExchange)

关于c# - 将 C# PageAsyncTask() 转换为 VB.Net 等效项时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55387465/

相关文章:

c# - 有什么方法可以访问公共(public)交通传奇中已发布事件的标题?

c# - 在 System.Windows.Form 派生类中的何处配置资源?

c# - 在 asp.net 中使用隐藏代码在页面加载时显示弹出 div?

c# - HttpClient 不使用 .NET Core 在 Windows 上发送客户端证书

vb.net - 某些 XP 系统获取 WMI 磁盘信息时出现 IO 异常

c# - 用大写字母和粗体格式化 RichTextBox 的第一行

.net - VB.Net 'Sub Main' 未找到

javascript - 我可以将 async wait 与 firebase 数据库调用一起使用吗?

node.js - 异步/等待 : Understanding problem with Async/Await

c# - 为什么在不使用 async/await 的情况下使用 Dapper QueryAsync<T> 时抛出 TaskCanceledException?