覆盖列表<t> .ToString()

时间:2017-11-01 16:14:40

标签: c#

好吧,我已经处于学习阶段,进行搜索并且没有找到,我想从我的列表中返回.ToString()&lt;&gt;但这在使用

using System.Collections.Generic; 
using System.Text;

namespace eciv {
    using Pontos = List<Ponto>;  // I need override ToString()

    public partial class FPrincipal : Form  {

        private void button1_Click(object sender, EventArgs e)  {
            Pontos aa = new Pontos();
            aa.Add(new Ponto(2, 3));
            aa.Add(new Ponto(3, 4));
            textBox1.Text = aa.ToString();  // here I need help  
        }
    }

    public class Ponto {

        public double X;
        public double Y;

        public Ponto() {}

        public Ponto(double x, double y) { 
            this.X = x; this.Y = y; 
        }

        public Ponto(Ponto p) { 
            this.X = p.X; 
            this.Y = p.Y; 
        }

        public override string ToString() {
            string s = "(" + this.X.ToString() + "," + this.Y.ToString() + ")";
            return s;
        }
    }   
}

在textBox中我得到了这个值

System.Collections.Generic.List`1[eciv.Ponto]

我想要这样的东西

((2,3),(3,4))

我认为就是这样,但它不起作用

public override string ToString() : Pontos {  
    StringBuilder s = new StringBuilder();
    s.Append("(");

    foreach (Ponto p in this) 
    {  
        s.Append(p.ToString() + ",");
    }

    s.Replace(",", ")", s.Length - 1, 1);
    return s.ToString();
}

3 个答案:

答案 0 :(得分:6)

如果您没有从该类继承,则无法覆盖某个类中的方法。所以解决方案很简单 - 不是创建名称别名,而是创建一个继承List<Ponto>

的类
public class Pontos : List<Ponto>
{
    public override string ToString() => $"({String.Join(",", this)})";
}

或格式化列表:

textBox1.Text = $"({String.Join(",", aa)})"; // consider use meaningful names for variables

如果你想将pontos列表只转换为字符串一次,我会选择第二个选项 - 字符串格式化不是引入新类型的好理由。

如果需要多次将此列表转换为字符串,可以创建一些私有或扩展方法来格式化对象列表(不是必需的Ponto对象)。 E.g。

public static string Stringify<T>(this IEnumerable<T> values)
   => $"({String.Join(",", values})";

使用

textBox1.Text = aa.Stringify(); // works with List<int> etc

链接:

答案 1 :(得分:1)

您可以创建自己的List<T>,它会覆盖ToString() - 方法

public class MyList<T> : List<T>
{
    public override string ToString()
    {
        StringBuilder s = new StringBuilder();
        s.Append("(");
        foreach (var element in this)
        {
            s.Append(element.ToString() + ",");
        }
        s.Replace(",", ")", s.Length - 1, 1);
        return s.ToString();
    }
}

答案 2 :(得分:0)

您可以根据为ToString()类创建的List<T>实现创建一个字符串,而不是在ToString()上调用Ponto,而不是这样:

Pontos aa = new Pontos();
aa.Add(new Ponto(2, 3));
aa.Add(new Ponto(3, 4));

StringBuilder s = new StringBuilder();
s.Append("(");
s.Append(String.Join(",", aa));
s.Append(")");

textBox1.Text = s.ToString();
相关问题