将枚举类型作为可选参数传递[重复]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

使用可选参数时,我喜欢将它们默认为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中创建“无”条目的负担之外,这与框架或第三方DLL定义的枚举无关。

vb.net
2个回答
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

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

从来没有使用过这个,所以任何评论/警告都是这样的,非常欢迎!

© www.soinside.com 2019 - 2024. All rights reserved.