原有问题
默认打印一个实体类对象时,并不会输出对应的属性值,例如有如下实体类:
public class Student
{
public int age { get; set; }
public string name { get; set; }
public List<String> subjects { get; set; }
}
对应控制台输入内容如下:
如果将class改为record,可一定程度上解决问题,但是遇到稍微复杂点的数据类型时,打印也会出问题
解决策略
此时可重写toString()方法解决
public class Student
{
public int age { get; set; }
public string name { get; set; }
public List<String> subjects { get; set; }
public override string ToString()
{
Type studentType = typeof(Student);
string result = "";
PropertyInfo[] propertyInfos = studentType.GetProperties();
foreach(PropertyInfo proc in propertyInfos)
{
// 获取名称
string name = proc.Name;
// 获取类型
string type = proc.PropertyType.Name;
// 获取值
object value = proc.GetValue(this) ;
// 根据数据类型,判断如何处理
if (type.Contains("List"))
{
string temp = "";
IList list = value as IList;
for (int i=0;i< list.Count; i++)
{
if(i== list.Count -1){
temp += (list[i].ToString());
}
else
{
temp += (list[i].ToString()) + ",";
}
}
value = temp;
}
else
{
value = value.ToString();
}
result += $@"{name}: {value}
";
}
return result;
}
}
此时控制台输出的内容如我们所愿
参考
关于使用反射的ToString()的c#:动态重写 | 码农家园 (codenong.com)