覆盖列表与LT的的ToString(); MyClass的> [英] Overriding ToString() of List<MyClass>

查看:158
本文介绍了覆盖列表与LT的的ToString(); MyClass的>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类MyClass的,我想重写名单的实例方法ToString():

 类MyClass的
{
公共字符串Property1 {搞定;组; }
公众诠释Property2 {搞定;组; }
/ * ... * /
公共重写字符串的ToString()
{
返回Property1.ToString()+ - + Property2.ToString();
}
}



我想有以下几点:

  VAR名单=新名单,LT; MyClass的> 
{
新MyClass的{Property1 =A,Property2 = 1},
新MyClass的{Property1 =Z,Property2 = 2},
};

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

是否可以这样做呢?或者,我会继承列表< MyClass的>覆盖t​​oString()方法在我的子类?我能解决使用扩展方法这个问题(即是否有可能覆盖使用扩展方法的方法)?



谢谢!


< DIV CLASS =h2_lin>解决方案

您需要子类覆盖任何方法。泛型的一点是说,你要相同的行为,无论T的类型如果你想为特定类型T的,那么你打破了合同,需要编写自己的类不同的行为:



 公共类MyTypeList:列表< MyClass的> 
{
公共重写字符串的ToString()
{
返回...
}
}






编辑补充:



没有,你无法通过创建一个扩展覆盖的方法,但你可以创建不同的签名的新方法是特定于该列表类型:

 公共静态字符串ExtendedToString(名单< MyClass的>清单)
{
返回....
}

 列表< MyClass的> myClassList =新的List< MyClass的> 
字符串输出= myClassList.ExtendedToString();



我还是觉得你虽然是最好的子类...


I have a class MyClass, and I would like to override the method ToString() of instances of List:

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

I would like to have the following:

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 */

Is it possible to do so? Or I would have to subclass List<MyClass> to override the method ToString() in my subclass? Can I solve this problem using extension methods (ie, is it possible to override a method with an extension method)?

Thanks!

解决方案

You'll need to subclass to override any method. The point of generics is to say that you want the same behaviour regardless of the type of T. If you want different behaviour for a specific type of T then you are breaking that contract and will need to write your own class:

public class MyTypeList : List<MyClass>
{
    public override string ToString()
    {
        return ...
    }
}


Edited to add:

No, you can't override a method by creating an extension, but you could create a new method with a different signature that is specific to this list type:

public static string ExtendedToString(this List<MyClass> list)
{
     return ....
} 

Used with

List<MyClass> myClassList = new List<MyClass>
string output = myClassList.ExtendedToString();

I still think you're better off subclassing though...

这篇关于覆盖列表与LT的的ToString(); MyClass的&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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