struct

2011-06-27 76 views
0

的一些基本练习好的,这是练习: 设置一个名为“Date”的结构,其中包含date,包括年,月和日。另外,定义一个名为“电话”的类,其中包含姓名,号码,出生日期和地址。需要创建一个包含Phone类型对象的数组,并按名称,数字和日期对它们进行排序。 这是我的代码:struct

struct Date 
{ 
    int year, month, day; 
    public Date(int year, int month, int day) 
    { 
     this.year = year; 
     this.month = month; 
     this.day = day; 
    } 
} 
class Phone 
{ 
    int number; 
    string birthday, adress, name; 
    public Phone(int number, string 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]; 
     for (int i = 0; i < p.Length; i++) 
     { 
     } 
    } 
} 

那么,事情是,我不知道如何从“手机”类获得结构的日期。 它假设是这样的权利?生日,年,等等。 谢谢。

+0

您应该从生日被称为“出生日期”这一事实中得到提示。你创建了一个Date结构体......现在使用它。 –

回答

1

您已将birthday声明为string。您需要将其声明为Date

1

那么,你目前得到了birthday作为一个字符串 - 我怀疑你实际上希望这是一个Date,对吧?将字段和构造函数参数设为Date

你也应该几乎可以肯定有所有值的“getter”属性 - 否则一旦你创建了struct实例,你就无法得到任何数据。

0

我不确定你要在这里做什么。您将“生日”作为字符串传递,而不是“日期”的实例。

如果你想要的生日是一个日期你需要这样做:

public class Phone 
{ 
    public int Number {get; set;} 
    public string Name {get; set;} 
    public Date Birthday {get; set;} 
    public string Address {get; set;} 

    public Phone(int number, Date birthday, string name, string address) 
    { /* your implementation here */ } 
} 

如果你想将字符串传递到您的手机构造的生日,你需要的东西日期结构将其转换为:

public Phone(int, number, string birthday, string name, string address) 
{ 
    Number = number; 
    Birthday = Date.FromString(birthday); 
    Name = name; 
    Address = address; 
} 

Date.FromString(string date)将是您的Struct中的方法。

+0

好吧,明白你告诉我,现在这是代码: –

0

你应该声明你的生日变量为日期。你不需要结构。