解析连接对象的值

时间:2018-05-08 11:23:08

标签: c# .net reflection

我的Person对象具有string nameint ageProfession profession等属性。专业有int idstring description等属性。

现在我想要的是将所有值提取到字符串中。该字符串应如下所示:

  

姓名:Mr.X,年龄:24岁,职业:{Id:1,描述:IT专家}

但是我的代码只能得到

  

姓名:Mr.X,年龄:24岁,职业:Models.Profession

我的代码是:

foreach (PropertyInfo pi in myObject.GetType().GetProperties())
{
    values += pi.Name + ": " + pi.GetValue(myObject) + ", ";
}

我做错了什么?请帮忙。

提前致谢:)

1 个答案:

答案 0 :(得分:1)

这样的事情可能会起到作用:

class Profession
{
    ...

    public override string ToString()
    {
        //return string.Format("{{Id: {0}, Description: {1}}}", Id, Description);
        string values = string.Empty;
        foreach (System.Reflection.PropertyInfo pi in myObject.GetType().GetProperties())
            values += pi.Name + ": " + pi.GetValue(myObject) + ", ";
        return values.Substring(0, Math.Max(0, values.Length - 2));
    }
}

编辑:如果你不想覆盖ToString()方法,那么这样会更好:

public class Person : AbstractClass
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Profession Profession { get; set; }
}

public class Profession : AbstractClass
{
    public int Id { get; set; }
    public string Description { get; set; }
}

public abstract class AbstractClass
{
    public string GetString()
    {
        string values = string.Empty;
        foreach (System.Reflection.PropertyInfo pi in GetType().GetProperties())
        {
            if (pi.PropertyType.IsSubclassOf(typeof(AbstractClass)))
                values += pi.Name + ": {" + (pi.GetValue(this) as AbstractClass).GetString() + "}, ";
            else
                values += pi.Name + ": " + pi.GetValue(this) + ", ";
        }
        return values.Substring(0, Math.Max(0, values.Length - 2));
    }
}