假设有这样一个类: Person{ public string name; public string age; public string sex; } 函数每次传入两个有序字符串数组, fun(string[] keys, string[] values), 像这样 keys = {"name", "age", "sex"}, values ={"小明", "20", "男"}, 怎么将传入的值组装成一个Person对象最简单?
public static Person InitPerson(string[] keys, string[] values) { Person person = new Person(); var len = keys.Length; for (int i = 0; i < len; i++) { person.GetType().GetField(keys[i]).SetValue(person,values[i]); } return person; }
var keys = new string[] { "name", "age", "sex" }; var values = new string[] { "小明", "20", "男" }; Dictionary<string, object> dict = new Dictionary<string, object>();
for (int i = 0; i < keys.Length; i++) { dict[keys[i]] = values[i]; } System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); var person = js.ConvertToType<Person>(dict);
建议传成Json格式,这样可以直接序列化和反序列化得到。
如果非要这样的话,写循环一个字段一个字段赋值吧。