反射可以在这里提供帮助,无需硬编码属性名称和使用第三方库
var person = Deserialize<Person2>("a.txt");
T Deserialize<T>(string fileName)
{
Type type = typeof(T);
var obj = Activator.CreateInstance(type);
foreach (var line in File.ReadLines(fileName))
{
var keyVal = line.Split('=');
if (keyVal.Length != 2) continue;
var prop = type.GetProperty(keyVal[0].Trim());
if (prop != null)
{
prop.SetValue(obj, Convert.ChangeType(keyVal[1], prop.PropertyType));
}
}
return (T)obj;
}
public class Person2
{
public int id { set; get; }
public string familyName { set; get; }
public string givenName { set; get; }
public string middleNames { set; get; }
public string dateOfBirth { set; get; }
public string dateOfDeath { set; get; }
public string placeOfBirth { set; get; }
public double height { set; get; }
public string twitterId { set; get; }
}