打印对象列表

时间:2017-06-01 05:56:31

标签: c#

我有以下课程,如何在C#中以[1,[2,3,8],[[]],10,[]]的格式打印对象列表?

public class InnerList
{
    private int val;
    private boolean isValue;
    private List<InnerList> intList;
}
public string ConvertToString()
{
    if (this.isValue)
    {
        return this.val + "";
    }
    else
    {
        return this.intList.ToString();
    }
}

在我的来电者中,我将使用下面的内容以[1,[2,3,8],[[]],10,[]]

格式打印对象列表
System.out.println(list);

我的问题是如何在c#中实现这个目标?

3 个答案:

答案 0 :(得分:1)

<强> Solution:

public class InnerList
{
    //public only for simple initialization at usage example
    public int val;
    public bool isValue;
    public List<InnerList> intList;

    public override string ToString()
    {
        if (isValue)            
            return val.ToString();                
        return String.Format("[{0}]", intList == null ? "" : String.Join(", ", intList.Select(x => x.ToString())));
    }
}  

<强>用法:

var test = new InnerList
{
    intList = new List<InnerList>  {
        new InnerList { isValue = true, val = 1 },
        new InnerList { isValue = true, val = 2 },
        new InnerList
        {
            intList = new List<InnerList>  {
                new InnerList { isValue = true, val = 13 },
                new InnerList { isValue = true, val = 23 },
                new InnerList()
            }
        }
    }
};
Console.WriteLine(test);//[1, 2, [13, 23, []]]

答案 1 :(得分:0)

欢迎来到C#世界!

我无法理解你想做什么,但我可以通过C#告诉你我们是怎么做的:

  public class InnerList
    {
        public int Value
        {
            get
            {
                return this.intList.Count;
            }
        }

        public bool HasValue { get; set; }

        private List<InnerList> intList;

        public static implicit operator string(InnerList list)
        {
            return list.ToString();
        }

        public override string ToString()
        {
            if (this.HasValue)
            {
                return this.Value.ToString();
            }
            else
            {
                return this.intList.ToString();
            }
        }
    }

答案 2 :(得分:0)

看起来你可能会遇到这里引用循环的问题。因为InnerList可以在其intList中引用其自己的父级。这就是为什么我会推荐一个序列化器来为你完成这项工作。它知道如何处理这些循环引用。我在这里使用Newtonsoft.Json

public override string ToString() 
{
    var settings = new JsonSerializerSettings();
    settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
    return JsonConvert.SerializeObject(this, settings);
}