【问题标题】:Problem on a struct exercise结构练习的问题
【发布时间】:2011-06-27 20:38:33
【问题描述】:

我目前正在学习结构,所以我有以下练习: 设置一个名为“Date”的结构,其中包含日期,包括:年、月和日。此外,定义一个名为 Phone 的类,其中包含姓名、号码、出生日期和地址。您需要创建一个包含 Phone 类型对象的数组,并按名称、编号和日期对它们进行排序。 好了,代码如下:

  struct Date
{
    int year, month, day;
    public Date(int year, int month, int day)
    {
        this.year = year;
        this.month = month;
        this.day = day;
    }
    public int Year
    {
        get { return year; }
        set {year = value; }
    }
    public int Month
    {
        get { return month; }
        set { month = value; }
    }
    public int Day
    {
        get { return day; }
        set { day = value; }
    }
}
    class Phone
{
    string number;
    string adress; 
    string name;
    Date birthday = new Date(); 
    public Phone(string number,Date birthday, string adress, string name)
    {
        this.number = number;
        this.birthday = birthday;
        this.adress = adress;
        this.name = name;
    }

}
class Program
{
    static void Main(string[] args)
    {
        Phone[] p = new Phone[3];
        p[0] = new Phone(1072548,
     }
}

我没有错误,但问题是我不知道如何从“日期”结构中获取生日,这就是我停止输入信息的原因。 谢谢。

【问题讨论】:

  • 为什么用 Class 创建日期?并使用 struct ?
  • 为什么要为具有生日属性的手机建模?是手机的生日吗?想要跟踪这是多么奇怪的事情。
  • 大声笑,我没听懂你们,你是说我做错了什么还是这个问题很愚蠢?
  • 你应该考虑使结构不可变。
  • Struct exercise 的可能重复项

标签: c#


【解决方案1】:
p[0] = new Phone(1072548,
   new Date (1999, 12, 31),
   "Central Park, NY", "Sam Party")

也许将其添加到您的 Date 结构中:

public DateTime ToDateTime ()
{
   return new DateTime (Year, Month, Day);
}

然后,您可以像这样对数组进行排序:

array.OrderBy (p => p.BirthDate.ToDateTime ());

【讨论】:

  • 谢谢!!另一件事,我是使用二进制搜索还是..对数组进行排序?
  • @Rich,看看我对这个问题的回答。它可能会有所帮助,但您可能需要我提到的网页中描述的非通用选项。 *.com/questions/6488201/…
【解决方案2】:
struct Date
{
    Date()
    {
       //code
    }
}

class Phone
{
    Phone(string "someParametr")
    {
      //code
    }
}

你需要两个承包商。

【讨论】: