How to create an extension method for ToString?

后端 未结 3 1379
独厮守ぢ
独厮守ぢ 2020-12-01 08:39

I have tried this:

public static class ListHelper
{
    public static string ToString(this IList list)
    {
        return string.Joi         


        
3条回答
  •  隐瞒了意图╮
    2020-12-01 09:43

    Simply you Shouldn't use the name ToString for the Extension method as it will never be called because that method already exist and you shouldn't use T as its useless there.

    For example i tried this and again it returned same thing:

    Console.WriteLine(lst.ToString());
    

    output:

    shekhar, shekhar, shekhar, shekhar
    

    so this time i used int and it still ran because that T has no use other then changing the Method Prototype.

    So simply why are you using ToString Literal as Method name, as it already exist and you can't override it in a Extension method, this is the reason you had to use that T to make it generic. Use some different name like

    public static string ToMyString(this IList list)
    

    That way you wouldn't have to use generic as it useless there and you could simply call it as always.


    That said your code is working for me. here is what i tried (in LINQPAD):

    void Main()
    {
    
        List lst = new List();
        lst.Add("shekhar");
        lst.Add("shekhar");
        lst.Add("shekhar");
        lst.Add("shekhar");
        lst.ToString().Dump();
    }
    
        public static class ListHelper
        {
            public static string ToString(this IList list)
            {
                return string.Join(", ", list.ToArray());
            }
    
            public static string ToString(this String[] array)
            {
                return string.Join(", ", array);
            }
        }
    

    And the output was shekhar, shekhar, shekhar, shekhar

    Since you have specified that T in ToString you will need to mention a Type like string or int while calling the ToString method.

提交回复
热议问题