【问题标题】:Is there a type which holds a Start- and End-DateTime in C#? [duplicate]在 C# 中是否存在包含开始日期时间和结束日期时间的类型? [复制]
【发布时间】:2023-04-02 05:17:01
【问题描述】:

我有一个方法,目前采用DateTime startDateDateTime endDate。如果有一个由两个 DateTime 组成的数据类型,那就太好了,这样我的方法就只需要一个值而不是两个。

我专门寻找单一类型,但如果不可能,我想我必须创建自己的 DatePeriod 类。

解决方案

在研究了一段时间后,我终于意识到我的问题没有完美的答案。 所以现在我创建了自己的类来保存这两个值,但元组也可以正常工作。

这是代码(与StepUp's Answer 中的几乎完全相同,但我使用的是结构):

public struct DatePeriod
{
    public DateTime Start { get; set; }
    public DateTime End { get; set; }

    public DatePeriod(DateTime startDate, DateTime endDate)
    {
        Start = startDate;
        End = endDate;
    }
}

【问题讨论】:

  • 嗯,你可以自己做DateRange类型。
  • @John 我会调查一下,谢谢!

标签: c# datetime variables types range


【解决方案1】:

其中一种方法是创建一个包含必要数据的类:

public class FooClass
{
    public DateTime StartDate { get; private set; }
    public DateTime EndDate { get; private set; }

    public FooClass(DateTime startDate, DateTime endDate)
    {
        StartDate = startDate;
        EndDate = endDate;
    }
}

并将其用作参数:

public void YourMethod(Fooclass foo)
{
}

还有an example of using Tuple

public void Tuple(Tuple<DateTime, DateTime> test) 
{}

In addition, you can read more DTO pattern.

【讨论】:

    【解决方案2】:

    您可以使用自定义模型:

    public class CustomDateRange
    {
        public DateTime Start {get;set;}
        public DateTime End {get;set;}
    }
    

    您可以使用 Tuple 类:

    var range = new Tuple <DateTime, DateTime>(start, end)
    

    或者您甚至可以使用元组类型:

    (DateTime, DateTime) range = (start, end)
    

    也许还有更多选择,但这些是我想到的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2018-01-30
      相关资源
      最近更新 更多