How to create an extension method for ToString?

后端 未结 3 1381
独厮守ぢ
独厮守ぢ 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:19

    It sounds like you want to replace what files.ToString() returns. You will not be able to do that without writing a custom class to assign files as (i.e. inherit from List and override ToString().)

    First, get rid of the generic type (), you're not using it. Next, you will need to rename the extension method because calling files.ToString()will just call the List's ToString method.

    This does what you're looking for.

    static class Program
    {
        static void Main()
        {
            var list = new List { {"a"}, {"b"}, {"c"} };
            string str = list.ToStringExtended();
        }
    }
    
    
    public static class ListHelper
    {
        public static string ToStringExtended(this IList list)
        {
            return string.Join(", ", list.ToArray());
        }
    }
    

提交回复
热议问题