Some basic exercise on struct
Alright, this is the exercise: Set a struct called "Dat开发者_如何转开发e" that contains date, including: year, month and day. Also, define a class called "Phone" that contains a name, number, date of birth and address. Need to create an array that contains objects of type Phone and sort them by name, number, and date. This is my code:
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++)
{
}
}
}
So, the thing is that I don't know how to get the struct date from the "Phone" class. It suppose to be something like this right? birthday.year, and such. Thanks.
You've declared birthday
as a string
.
You need to declare it as a Date
.
Well, you've currently got birthday
as a string - I suspect you actually want that to be a Date
, right? Make both the field and the constructor parameter a Date
.
You should also almost certainly have "getter" properties for all the values - otherwise you can't get at any of the data once you've created the struct instance.
I'm not sure what you're trying to do here. You're passing your "birthday" as a string, not as an instance of 'Date.'
If you want birthday to be a Date you'd need to do this:
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 */ }
}
If you wanted to pass a string to your Phone constructor for the birthday, you'd need something on the Date Struct to convert it:
public Phone(int, number, string birthday, string name, string address)
{
Number = number;
Birthday = Date.FromString(birthday);
Name = name;
Address = address;
}
and that Date.FromString(string date)
would be a method in your Struct.
You should declare your birthday variable as a Date. You wouldn't be needing the struct.
精彩评论