如何创建的toString扩展方法?

编程入门 行业动态 更新时间:2024-10-27 18:28:20
本文介绍了如何创建的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扩展方法?

本文发布于:2023-11-04 00:34:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556472.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   toString

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!