C# 如何在[]数组中重写ToString()?

C# 如何在[]数组中重写ToString()?,c#,.net,arrays,overriding,C#,.net,Arrays,Overriding,比如说,如果我需要覆盖自定义列表中的ToString方法,我会这样做: public class WebUILanguage2 : List<WebUILanguage> { public override string ToString() { return "Overridden message"; } } 你不能。不能从数组类型派生 我通常建议不要在列表中覆盖到字符串——根据我的经验,对于这样的事情,通常最好使用组合而不是继承。如前所述

比如说,如果我需要覆盖自定义
列表中的
ToString
方法,我会这样做:

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

你不能。不能从数组类型派生


我通常建议不要在
列表中覆盖
到字符串
——根据我的经验,对于这样的事情,通常最好使用组合而不是继承。

如前所述,你不能这样做。但作为一种解决方法,您只需编写一个新的 方法:

或功能:

using System;
class Program {
   static string Str(string[] a) => String.Join(',', a);
   static void Main() {
      string[] a = {"May", "June"};
      Console.WriteLine(Str(a));
   }
}
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));
   }
}
或通用函数:

using System;
class Program {
   static string Str(string[] a) => String.Join(',', a);
   static void Main() {
      string[] a = {"May", "June"};
      Console.WriteLine(Str(a));
   }
}
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));
   }
}
使用System.Collections.Generic;
使用制度;
班级计划{
静态字符串Str(IEnumerable a)=>string.Join(',',a);
静态void Main(){
字符串[]a={“五月”、“六月”};
控制台写入线(Str(a));
}
}

我只需要一个自定义的
ToString
方法。所以,也不是这样,哈?@ahmd0您可以使用扩展方法,例如,
IList
,并以您想要的方式打印它。@ahmd0:不是。您不能创建自己的类型来扩展数组类型。这在C#中是不可能的。@SargeBorsch:不过您需要给它一个不同的名称-just
ToString()
永远不会被作为扩展方法调用,因为只有在正常的成员查找失败时才会参考扩展方法。@ahmd0:恐怕您需要以不同的方式设计它。您可能可以将某些属性应用于属性,以便
PropertyGrid
以不同的方式显示它-但您将无法覆盖
ToString
。好吧,您的建议甚至无效,因此进一步询问此类情况是浪费时间。对于一般情况,这是正确的,但(从注释中)OP希望PropertyGrid自动拾取正确的表示