【问题标题】:C#: How can I create property (read-only) that shows hoursC#:如何创建显示小时数的属性(只读)
【发布时间】:2021-12-29 20:12:25
【问题描述】:

我有一个带有构造函数的结构:

public struct Time
{
    public Time(int minutes)
        : this()
    {
        this.Minutes = minutes;
    }

    public Time(int hours, int minutes)
        : this(minutes)
    {
        this.Hours = hours;
    }

我需要帮助来创建一个属性(只读),它允许我以 24 小时格式( 00.XX - 23.XX )指示小时数。如上所述,我通过调用构造函数来提供属性的值。我目前未完成的尝试:

public readonly int Hours { get; }

很高兴听到任何建议。干杯!

【问题讨论】:

  • 你为什么不用TimeSpan
  • 很遗憾,我不允许使用 TimeSpan。这是一项任务。
  • 你可以为你的get { return something; }提供一个块

标签: c# constructor


【解决方案1】:
public struct Time
{
    public Time(int minutes)
        : this()
    {
        this.Minutes = minutes;
    }

    public Time(int hours, int minutes)
        : this(minutes)
    {
        this.Hours = hours%23;
    }

    public int Hours {get;set;}
    public int Minutes {get;set;}

    public string To24Hours{get {
        return $"{this.Hours} : {this.Minutes}";
    }}
}

这要求您确保在构造函数中输入的时间已经是 24 小时格式。

【讨论】:

  • 你能告诉我为什么我可以确保吗?
  • 取决于您的输入源...您从哪里获得时间?换句话说,您是在显示当前时间还是您的问题涉及接收时间值然后转换为 21 小时
  • 对于 Hours 输出应该看起来像这样 0 -> 0 1 -> 1 23 -> 23 24 -> 0 25 -> 1 所以如果例如输入是 26 输出应该是 2 。我需要以某种方式在构造函数中应用这个逻辑。也许使用 % 运算符。 25 % 24 = 1
  • 从您的解释看来,您已经使用 % 运算符对 Hours 的处理进行了排序,然后再将其传递给构造函数,或者您可以在构造函数级别进行操作
  • 你能告诉我如何在构造函数级别做到这一点吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 2014-04-26
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多