如何创建的toString扩展方法? [英] How to create extension method for toString?

查看:158
本文介绍了如何创建的toString扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经试过这种

public static class ListHelper
{
    public static string ToString<T>(this IList<String> list)
    {
        return string.Join(", ", list.ToArray());
    }

    public static string ToString<T>(this String[] array)
    {
        return string.Join(", ", array);
    }
}



但它不工作,都为的String []和列表。也许我需要一些特殊的注解?

but it does not work, both for string[] and List. Maybe I need some special annotations?

推荐答案

扩展方法只检查是否存在的没有适用的候选方法那场比赛。在通话的ToString方法的情况下会有的总是的是适用的候选方法,即对对象的ToString。的扩展方法的目的是要的延伸的的方法集可在一个类型,而不是<青霉>倍率的现有的方法;这就是为什么他们是所谓的扩展方法。如果要覆盖现有的方法,那么你就必须做出一个压倒一切的方法。

Extension methods are only checked if there are no applicable candidate methods that match. In the case of a call to ToString there will always be an applicable candidate method, namely, the ToString on object. The purpose of extension methods is to extend the set of methods available on a type, not to override existing methods; that's why they're called "extension methods". If you want to override an existing method then you'll have to make an overriding method.

这篇关于如何创建的toString扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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