使用可选参数时,我喜欢将它们默认为Nothing
.
Sub DoSomething(ByVal Foo as String, Optional ByVal Bar as String = Nothing)
If Bar IsNot Nothing then DoSomethingElse(Bar)
DoAnotherThing(Foo)
End Sub
这很有效,除非您开始使用Enum
类型(或 anInteger
和其他数据类型)。在这种情况下,我的Enum
列表包含一个“无”值,如下所示:
Enum MyEnum
None
ChoiceA
ChoiceB
End Enum
Sub DoSomething(ByVal Foo as String, Optional ByVal Bar as MyEnum= MyEnum.None)
If Bar = MyEnum.None then DoSomethingElse(Bar)
DoAnotherThing(Foo)
End Sub
它有效,但我正在寻找替代方案。除了在 custom 中创建“None”条目的负担之外Enum
,这对于框架或第三方 DLL 定义的枚举是不可能的。
通常情况下,我在起草问题时遇到了一些答案。
这篇文章和.NetDocumentation建议使用可空值:
Sub DoSomething(ByVal Foo as String, Optional ByVal Bar as Nullable(Of MyEnum) = Nothing)
If Bar IsNot Nothing then DoSomethingElse(Bar)
DoAnotherThing(Foo)
End Sub
或者,
Sub DoSomething(ByVal Foo as String, Optional ByVal Bar as Nullable(Of MyEnum) = Nothing)
If Bar IsNot Nothing then DoSomethingElse(Bar)
DoAnotherThing(Foo)
End Sub
从来没有使用过这个所以任何评论/警告都是最受欢迎的!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句