c# - 在函数中设置可选参数需要常量表达式错误

标签 c# vb.net

为什么我得到一个

Constant Expression Required

以下 VB.net 代码有错误吗?

Public Shared Async Function DownloadAndCountBytesAsync(url As String, Optional token As CancellationToken = New CancellationToken) As Task(Of Integer)

Nothing 交换 New CancellationToken 并添加

If token = Nothing Then token = New CancellationToken

该函数有效,但我不明白为什么第一个选项不起作用...

同样的事情似乎在 C# 中工作得很好

public static async Task<int> DownloadAndCountBytesAsync(string url, CancellationToken token = new CancellationToken())

最佳答案

VB 中可选参数的默认值必须在编译时已知,这意味着它必须是文字、声明的常量或Nothing。这意味着除 String 之外的任何引用类型只能具有默认值 Nothing

实现你想要的方法是重载方法:

Public Shared Async Function DownloadAndCountBytesAsync(url As String) As Task(Of Integer)
    Return DownloadAndCountBytesAsync(url, New CancellationToken)
End Function

Public Shared Async Function DownloadAndCountBytesAsync(url As String, token As CancellationToken) As Task(Of Integer)
    '...'
End Function

关于c# - 在函数中设置可选参数需要常量表达式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29337364/

相关文章:

c# - 在后台播放声音

c# - REngine rengine = REngine.CreateInstance ("RDotNet", new[] { "-q"} 在第二次调用时进一步停止执行

asp.net - 添加数据表和包含数据表的 session

c# - 首次运行时自动运行 Ngen.exe

c# - 通用对象池

c# - 调用另一个具有表单例份验证的应用程序的 API

c# - 如何从图片url中解析出图片名称

.net - 将标签和值绑定(bind)到 ComboBox Winforms

c# - VB.NET 与 C# 整数除法

c# - VB转C#帮助(?运算符)