vb.net 在可选数组参数中指定默认数组值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22611560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Specifying default array values in an optional array parameter
提问by ingredient_15939
Optional parameters require default values, yet I can't seem to assign a default array to an optional array parameter. For example:
可选参数需要默认值,但我似乎无法将默认数组分配给可选数组参数。例如:
Optional ByVal myArray As Long() = Nothing ' This works
However
然而
Optional ByVal myArray As Long() = New Long() {0, 1} ' This isn't accepted.
The IDE tells me that a "constant expression is required" in place of New Long() {0, 1}.
IDE 告诉我“需要常量表达式”来代替New Long() {0, 1}.
Is there a trick to assigning a default array of constants, or is it not allowed?
是否有分配默认常量数组的技巧,还是不允许?
回答by Hans Passant
It is not a "constant expression", an expression that can be entirely evaluated at compile time and produces a single simple value that can be stored in the assembly metadata. To be used, later, in other code that makes the call. Optional values are retrieved at compile time, not runtime, strictly a compiler feature.
它不是一个“常量表达式”,一个可以在编译时完全计算并生成一个可以存储在程序集元数据中的简单值的表达式。稍后在进行调用的其他代码中使用。在编译时检索可选值,而不是运行时,严格来说是编译器功能。
The Newoperator must be executed at runtime and requires code to do so. And is therefore not a constant expression. The simple workaround is to use Nothing and put the code in the method body:
在新的运营商必须在运行时执行,并且需要的代码这样做。因此,它不是一个常量表达式。简单的解决方法是使用 Nothing 并将代码放在方法体中:
Sub Foo(Optional ByVal myArray As Long() = Nothing)
If myArray Is Nothing Then myArray = New Long() {0, 1}
'' etc...
End Sub

