如何为ToString创建扩展方法? [英] How to create an extension method for ToString?

查看:113
本文介绍了如何为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);
    }
}

但是对于<$ c都无效$ c> string [] 和 List< string> 。也许我需要一些特殊的注释?

But it does not work, both for string[] and List<string>. 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天全站免登陆