我怎么可以重写ToString()方法对所有的IEnumerable<的Int32>? [英] How can I override ToString() method for all IEnumerable<Int32>?

查看:166
本文介绍了我怎么可以重写ToString()方法对所有的IEnumerable<的Int32>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要重写的ToString()的IEnumerable<的Int32>

我想用扩展方法。

但是,当我做到这一点的下方,它仍然会调用的ToString() System.Object的。当我重新命名我的方法,然后调用我的方法。

由于我的扩展方法是一个静态类,我不能覆盖。

我怎么能做到这一点,使我的的ToString()当我打电话的实施被称为的ToString()名单,其中,的Int32> 例如:

 公共静态类ExtensionMethods
{
    公共静态新字符串的ToString(这IEnumerable的<的Int32>集)
    {
        VAR SB =新的StringBuilder();

        //请在SB一些修改

        返回sb.ToString();
    }
}
 

解决方案
  

我怎么能做到这一点,使我的ToString()实现被称为当我打电话的ToString()的列表,例如?

您不能,基本上是这样。扩展方法的只有的使用,如果没有匹配的实例方法都可以找到。

我建议你给你的方法不同的名称,避免了这个问题 - 和潜在的混乱你的方法会导致

请注意,即使扩展方法的的在preference匹配的对象声明(说)的方法,只会使差异为自己的code被用适当的编译使用指令 - 没有任何其他的code这已经绑定呼叫转移到正常的

如果您可以提供有关你想达到什么样的信息,我们也许能够帮助你更 - 但就目前而言,像 ToDelimitedString (或不管你的方法做)听起来像是对我来说是最好的选择。

I want to override ToString() on IEnumerable<Int32>.

I was thinking to use Extension methods.

But when I do this below, it still calls the ToString() on System.Object. When I rename my method, then it calls my method.

As my extension method is in a static class, I am not able to override.

How can I achieve this so that my ToString() implementation is called when I call .ToString() on List<Int32> for example?

public static class ExtensionMethods
{
    public static new string ToString(this IEnumerable<Int32> set)
    {
        var sb = new StringBuilder();

        // Do some modifications on sb

        return sb.ToString();
    }
}

解决方案

How can I achieve this so that my ToString() implementation is called when I call .ToString() on List for example?

You can't, basically. Extension methods are only used if no matching instance method can be found.

I suggest you give your method a different name, avoiding the problem - and the potential confusion your method would cause.

Note that even if extension methods were matched in preference to (say) methods declared on object, it would only make a difference for your own code being compiled with an appropriate using directive - not any other code which has already bound the call to the normal one.

If you can give more information about what you're trying to achieve, we may be able to help you more - but for the moment, something like ToDelimitedString (or whatever your method does) sounds like the best bet to me.

这篇关于我怎么可以重写ToString()方法对所有的IEnumerable&LT;的Int32&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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