我如何重写的ToString(),并实现通用? [英] How do I override ToString() and implement generic?

查看:214
本文介绍了我如何重写的ToString(),并实现通用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我想要做如下修改code:

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

  1. 我如何重写的ToString()?它说:静态成员...的ToString(System.Collections.Generic.List)'不能被标记为覆盖,虚拟或抽象的

  1. How do I override ToString()? It says: A static member ...ToString(System.Collections.Generic.List)' cannot be marked as override, virtual, or abstract.

我如何使它通用?

public static override string ToString(this List<int> list) {
    string output = "";
    list.ForEach(item => output += item.ToString() + "," );
    return output;
}

谢谢!

推荐答案

什么是你想达到什么目的?我常常想输出列表的内容,所以我创建了以下扩展方法:

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<string> 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<T>(this IEnumerable<T> 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<T>(this IEnumerable<T> 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

这篇关于我如何重写的ToString(),并实现通用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆