Does Array.ToString() provide a useful output?

前端 未结 6 1022
北海茫月
北海茫月 2020-12-03 13:31

If I have an array and perform a ToString() does that just string together the array values in one long comma seperated string or is that not possible on an arr

6条回答
  •  被撕碎了的回忆
    2020-12-03 14:12

    You can use string.Concat(Object[] args). This calls the ToString() method of every object in args. In a custom class you can override the ToString() method to achieve custom string conversion like this:

    public class YourClass
    {
        private int number;
    
        public YourClass(int num)
        {
            number = num;
        }
    
        public override string ToString()
        {
            return "#" + number;
        }
    }
    

    Now you can concatenate an array of instances of your custom class:

    YourClass[] yourArray = { new YourClass(1), new YourClass(2), new YourClass(3) };
    string concatenated = string.Concat(yourArray);
    

    Unfortunately this method does not add any delimiters, but I found it to be elegant. The variable concatenated will contain "#1#2#2".

提交回复
热议问题