简体   繁体   English

如何覆盖 [] 数组中的 ToString()?

[英]How to override ToString() in [] array?

Say, if I need to override ToString method in a custom List , I'd do this:说,如果我需要在自定义List覆盖ToString方法,我会这样做:

public class WebUILanguage2 : List<WebUILanguage>
{
    public override string ToString()
    {
        return "Overridden message";
    }
}

but what if I want to override this?但是如果我想覆盖它呢?

public class WebUILanguage2 : WebUILanguage[]

You can't.你不能。 You can't derive from array types.您不能从数组类型派生。

I'd generally advise against overriding ToString in List<T> , too - usually it's better to use composition than inheritance for things like this, in my experience.我通常也建议不要在List<T>中覆盖ToString - 根据我的经验,对于这样的事情,通常最好使用组合而不是继承。

As was said, you cant do that.如前所述,你不能那样做。 But as a workaround, you can simply write a new method:但作为一种解决方法,您可以简单地编写一个新方法:

using System;
static class Program {
   static string Str(this string[] a) => String.Join(',', a);
   static void Main() {
      string[] a = {"May", "June"};
      Console.WriteLine(a.Str());
   }
}

Or function:或函数:

using System;
class Program {
   static string Str(string[] a) => String.Join(',', a);
   static void Main() {
      string[] a = {"May", "June"};
      Console.WriteLine(Str(a));
   }
}

Or a generic function:或者一个通用函数:

using System.Collections.Generic;
using System;
class Program {
   static string Str(IEnumerable<string> a) => String.Join(',', a);
   static void Main() {
      string[] a = {"May", "June"};
      Console.WriteLine(Str(a));
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM