如何为 Nullable 和 Not Nullable 编写扩展方法

发布于 2024-10-01 15:27:09 字数 898 浏览 4 评论 0原文

我已经编写了以下扩展方法

    <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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我纯我任性 2024-10-08 15:27:09

我会选择第二个选择。不幸的是,当在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文