如何为 Nullable 和 Not Nullable 编写扩展方法
我已经编写了以下扩展方法
<Extension()>
Public Function ToUtcIso8601(ByVal dt As Date) As String
Return String.Format("{0:s}Z", dt)
End Function
,但我还需要同一方法的可为空版本...我到底该怎么做?
这就是我的想法,但我不确定这是否是正确的方法
<Extension()>
Public Function ToUtcIso8601(ByVal dt As Date?) As String
Return If(dt, Nothing).ToUtcIso8601()
End Function
或另一种选择,
<Extension()>
Public Function ToUtcIso8601(ByVal dt As Date?) As String
Return If(Not dt Is Nothing, ToUtcIso8601(dt), Nothing)
End Function
我只是不确定执行此操作的“正确”方法。
编辑
这确实有效,但是......
Public Function ToUtcIso8601(ByVal dt As Date?) As String
Return If(Not dt Is Nothing, ToUtcIso8601(dt.Value), Nothing)
End Function
这是正确的方法吗?
I've written the following Extension Method
<Extension()>
Public Function ToUtcIso8601(ByVal dt As Date) As String
Return String.Format("{0:s}Z", dt)
End Function
But I also need a Nullable version of the same method... how exactly do I do this?
This is what I was thinking, but I'm not sure if this is the right way
<Extension()>
Public Function ToUtcIso8601(ByVal dt As Date?) As String
Return If(dt, Nothing).ToUtcIso8601()
End Function
or another option
<Extension()>
Public Function ToUtcIso8601(ByVal dt As Date?) As String
Return If(Not dt Is Nothing, ToUtcIso8601(dt), Nothing)
End Function
I'm just not sure the "right" way to do this.
Edited
This actually works, But...
Public Function ToUtcIso8601(ByVal dt As Date?) As String
Return If(Not dt Is Nothing, ToUtcIso8601(dt.Value), Nothing)
End Function
Is this the right way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会选择第二个选择。不幸的是,当在 Date 结构上使用扩展方法时,Date?扩展方法不适用,否则您可以只为日期声明一个扩展?类型。您必须采用与现有方法类似的方法才能支持这两种类型。
I'd go for the second option. Unfortunately, when using extension methods on a Date struct, Date? extension methods are not applicable, otherwise you could just declare one extension for the Date? type. You will have to take a similar approach to the one you already have in order to support both types.