c# - 覆盖 List<MyClass> 的 ToString()

标签 c# string extension-methods overriding tostring

我有一个 MyClass 类,我想覆盖 List 实例的 ToString() 方法:

class MyClass
{
    public string Property1 { get; set; }
    public int Property2 { get; set; }
    /* ... */
    public override string ToString()
    {
        return Property1.ToString() + "-" + Property2.ToString();
    }
}

我想要以下内容:

var list = new List<MyClass>
            {
                new MyClass { Property1 = "A", Property2 = 1 },
                new MyClass { Property1 = "Z", Property2 = 2 },
            };

Console.WriteLine(list.ToString());   /* prints: A-1,Z-2 */

有可能吗?或者我必须继承 List 来覆盖我子类中的方法 ToString() ?我可以使用扩展方法解决这个问题吗(即,是否可以使用扩展方法覆盖方法)?

谢谢!

最佳答案

可能有点跑题了,不过我用的是ToDelimitedString适用于任何 IEnumerable<T> 的扩展方法.您可以(可选)指定要使用的分隔符和委托(delegate)来为每个元素执行自定义字符串转换:

// if you've already overridden ToString in your MyClass object...
Console.WriteLine(list.ToDelimitedString());
// if you don't have a custom ToString method in your MyClass object...
Console.WriteLine(list.ToDelimitedString(x => x.Property1 + "-" + x.Property2));

// ...

public static class MyExtensionMethods
{
    public static string ToDelimitedString<T>(this IEnumerable<T> source)
    {
        return source.ToDelimitedString(x => x.ToString(),
            CultureInfo.CurrentCulture.TextInfo.ListSeparator);
    }

    public static string ToDelimitedString<T>(
        this IEnumerable<T> source, Func<T, string> converter)
    {
        return source.ToDelimitedString(converter,
            CultureInfo.CurrentCulture.TextInfo.ListSeparator);
    }

    public static string ToDelimitedString<T>(
        this IEnumerable<T> source, string separator)
    {
        return source.ToDelimitedString(x => x.ToString(), separator);
    }

    public static string ToDelimitedString<T>(this IEnumerable<T> source,
        Func<T, string> converter, string separator)
    {
        return string.Join(separator, source.Select(converter).ToArray());
    }
}

关于c# - 覆盖 List<MyClass> 的 ToString(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1340128/

相关文章:

c# - 对于 Windows Phone 7, "assembly"是什么?

c# - 在 monoTouch 中格式化大量数据

c - 如何从c中的字符串数组中删除一个字符串

c# - 处理列表的扩展方法不起作用

f# - 如何在 F# 测量单位上定义扩展成员?

c# - 财务计算 : double or decimal?

C# - StreamReader.ReadLine 无法正常工作!

java - 传递 2 个字符串以用于新 Activity

string - Swift 3 字符串插入

c# - 扩展方法未设置值