How do I override ToString() and implement generic?

前端 未结 4 1268
温柔的废话
温柔的废话 2021-01-16 09:33

I have code that I want to make the following changes:

  1. How do I override ToString()? It says: A static member ...ToString(System.Collections.Generic.List)\'

4条回答
  •  逝去的感伤
    2021-01-16 09:54

    What are you trying to achieve? Often I want to output the contents of a list, so I created the following extension method:

    public static string Join(this IEnumerable strings, string seperator)
    {
        return string.Join(seperator, strings.ToArray());
    }
    

    It is then consumed like this

    var output = list.Select(a.ToString()).Join(",");
    

    EDIT: To make it easier to use for non string lists, here is another variation of above

    public static String Join(this IEnumerable enumerable, string seperator)
    {
        var nullRepresentation = "";
        var enumerableAsStrings = enumerable.Select(a => a == null ? nullRepresentation : a.ToString()).ToArray();
        return string.Join(seperator, enumerableAsStrings);
    }
    
    public static String Join(this IEnumerable enumerable)
    {
        return enumerable.Join(",");
    }
    

    Now you can consume it like this

    int[] list = {1,2,3,4};
    Console.WriteLine(list.Join()); // 1,2,3,4
    Console.WriteLine(list.Join(", ")); // 1, 2, 3, 4
    Console.WriteLine(list.Select(a=>a+".0").Join()); // 1.0, 2.0, 3.0, 4.0
    

提交回复
热议问题