字典包含键值对。密钥必须是唯一的。所以在这种情况下,字典不是一个好方法。
你必须先构建一个领域模型:
//This will hold your user information
public class UserInfo
{
public string Name { get; set; }
public string Email { get; set; }
public string Location { get; set; }
public int Age { get; set; }
public string Phone { get; set; }
}
//this other class is called a viewmodel which combains your user and the question posed by the user
public class FormData
{
public UserInfo user { get; set; }
public string question { get; set; }
}
//this class is your public facing interface which will interact with the user/front-end form
public class Questionaire
{
FormData _data;
public void FillForm(FormData data)
{
//do whatever you want with the data
//save to database, send by email, whatever
_data = data;
}
}
class Program
{
static void Main(string[] args)
{
//this is how you use it to collect data from the user
Questionaire questionaire = new Questionaire();
questionaire.FillForm(new FormData
{
question = "your question goes here",
user = new UserInfo
{
Name = "YourName",
Age = 20,
Email = "someemail",
Location = "yourlocation",
Phone = "0123665555"
}
});
}
}
选项 2(因为您坚持使用字典):
public class UserInfo
{
public string Name { get; set; }
public string Email { get; set; }
public string Location { get; set; }
public int Age { get; set; }
public string Phone { get; set; }
}
Dictionary<string, UserInfo> _values;
public void FillForm(Dictionary<string, UserInfo> values)
{
_values = values;
}
//You call it like this:
Dictionary<string, UserInfo> dic = new Dictionary<string, UserInfo>();
dic.Add("question1", new UserInfo { Age = 20, Name = "Name1" });
dic.Add("question2", new UserInfo { Age = 20, Name = "Name2" });
Form form = new Form();
form.FillForm(dic);
选项 3,但这不是可行的方法:
public class Form2
{
Dictionary<string, string> _values;
public void FillForm(Dictionary<string, string> values)
{
_values = values;
}
}
Dictionary<string, string> user1 = new Dictionary<string, string>();
user1.Add("question1", "Users question goes here");
user1.Add("Name", "name1");
user1.Add("Age", "age");
//...
var form2 = new Form2();
form2.FillForm(user1);