我需要让我的第二个嵌套for循环将数组值发送给类朋友。 我不知道怎么回事? 除非我在课堂上遗漏了什么?
namespace List
{
class Program
{
public const int ARRAYSIZE = 5;
static void Main()
{
string[] relSend = { "Enter name", "enter phone number", "enter 2 didigt month dob", "enter 2 digit day dob", "enter 2 digit dob year" };
string[] In = new string[5];
string[] answer = new string[10];
for (int x = 0; x <= 8; x++)
{
for (int i = 0; i < relSend.Length; i++)
{
WriteLine("{0}", relSend[i]);
In[i] = Console.ReadLine();
}
for (int i = 0; i < In.Length; i++)
{
}
}
}
}
}
public class Friends
{
public string Name { get; set; }
public int Phone { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
答案 0 :(得分:1)
我猜你的意思是你想要从所收集的信息中创建一个对象,这没问题:
List<Friend> friends = new List<Friend>();
for (int x = 0; x <= 8; x++)
{
for (int i = 0; i < relSend.Length; i++)
{
WriteLine("{0}", relSend[i]);
In[i] = Console.ReadLine();
}
friends.Add( new Friend() { Name = In[0]
, Phone = int.Parse(In[1])
, Month = int.Parse(In[2])
, Day = int.Parse(In[3])
, Year = int.Parse(In[4])
}
);
}
确保在创建对象之前验证输入!此外,我建议您使用string
作为电话号码,因为您将丢失通常前缀0
。 Month
,Day
和Year
可能合并为一个DateTime
。
答案 1 :(得分:0)
告诉我您是否需要任何解释:
namespace List
{
class Program
{
//Create a dictionary to find out each question is realated to which property.
private static Dictionary<string, string> questions = new Dictionary<string, string>();
static void Main()
{
questions.Add("Enter name", "Name");
questions.Add("enter phone number", "Phone");
questions.Add("enter 2 didigt month dob", "Month");
questions.Add("enter 2 digit day dob", "Day");
questions.Add("enter 2 digit dob year", "Year");
//Create list of friends
List<Friends> friendsList = new List<Friends>();
for (int x = 0; x <= 8; x++)
{
Friends f = new Friends();
foreach (string q in questions.Keys)
{
Console.WriteLine("{0}", q);
//Find property using Sytem.Reflection
System.Reflection.PropertyInfo property = f.GetType().GetProperty(questions[q]);
//Set value of found property
property.SetValue(f, Convert.ChangeType(Console.ReadLine(), property.PropertyType), null);
}
//Add a friend to list
friendsList.Add(f);
}
}
}
}
public class Friends
{
public string Name { get; set; }
public int Phone { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}