Main
public static void Main(string[] args) { var list = new List<string>(); list.Add("1"); list.Add("Tom"); list.Add(""); list.Add("1234@sss"); var model = new TestModel(); var properties = model.GetType().GetProperties(); for (int i = 0; i < properties.Count(); i++) { var type = properties[i].PropertyType; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { if (string.IsNullOrEmpty(list[i])) { properties[i].SetValue(model, null, null); continue; } type = Nullable.GetUnderlyingType(type); } properties[i].SetValue(model, Convert.ChangeType(list[i], type), null); } Console.ReadKey(); }
Model
public class TestModel { public int No { get; set; } public string Name { get; set; } public int? Age { get; set; } public string Email { get; set; } }
努力的小佳