Vb.net 将枚举类型作为可选参数传递

Vb.net 将枚举类型作为可选参数传递,vb.net,Vb.net,使用可选参数时,我喜欢将它们默认为无 Sub DoSomething(ByVal Foo as String, Optional ByVal Bar as String = Nothing) If Bar IsNot Nothing then DoSomethingElse(Bar) DoAnotherThing(Foo) End Sub 这非常有效,除非您开始使用Enum类型(或Integer和其他数据类型)。 在这种情况下,我的Enum列表包含一个“None”值,如下所示:

使用可选参数时,我喜欢将它们默认为

Sub DoSomething(ByVal Foo as String, Optional ByVal Bar as String = Nothing)
    If Bar IsNot Nothing then DoSomethingElse(Bar)
    DoAnotherThing(Foo)
End Sub
这非常有效,除非您开始使用
Enum
类型(或
Integer
和其他数据类型)。 在这种情况下,我的
Enum
列表包含一个“None”值,如下所示:

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

这是可行的,但我正在寻找替代方案。除了在自定义的
Enum
中创建“None”条目的负担之外,这对于框架或第三方DLL定义的枚举来说是不可能的。

通常情况下,我在起草问题时遇到了一些答案

这和建议建议使用可为空的:

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, ByVal Bar as MyEnum)
    DoSomethingWithBar(Bar)
    DoSomething(Foo)
End Sub

Sub DoSomething(ByVal Foo as String)
    ' Do something with Foo
End Sub

在某些情况下,我确实广泛使用了重载,但在某些情况下,
可选
的好处会胜出。一般来说,我发现重载会降低可读性,使代码维护更容易出错。话虽如此,它的优点是提供了不同的XML文档标记。您也没有None、Nullable和If。这无疑是None的优势。如果
Nullable
不是备选方案,我会选择重载。可为null的参数将是备选方案,
As MyEnum?=无任何内容
作为字符串的ByVal Foo,可选的ByVal条作为MyEnum?=因为用于声明枚举的基础类型不能为空,所以任何东西都不起作用。
Sub DoSomething(ByVal Foo as String, ByVal Bar as MyEnum)
    DoSomethingWithBar(Bar)
    DoSomething(Foo)
End Sub

Sub DoSomething(ByVal Foo as String)
    ' Do something with Foo
End Sub