传递Enum类型作为可选参数

时间:2019-04-17 12:04:55

标签: vb.net

使用可选参数时,我希望将其默认设置为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类型(或Integer和其他数据类型)。 在这种情况下,我的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

它可以工作,但是我正在寻找替代方法。除了在自定义Enum中创建“ None”条目的负担之外,使用框架或第三方DLL定义的枚举也是不可能的。

2 个答案:

答案 0 :(得分:1)

在起草问题时,通常会遇到一些答案。

post.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

从未使用过,因此任何以这种方式发表的评论/警告都非常受欢迎!

答案 1 :(得分:1)

在您的示例中,重载可能更有意义。

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
相关问题