首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往
首页标签tostring

#tostring

如何重写List<MyClass>的ToString()?

小羊驼知足常乐。
我用的是ToDelimitedString可扩展方法: // if you've already overridden ToString in your MyClass object... Console.WriteLine(list.ToDelimitedString()); // if you don't have a custom ToString method in your MyClass object... Console.WriteLine(list.ToDelimitedString(x => x.Property1 + "-" + x.Property2)); // ... public static class MyExtensionMethods { public static string ToDelimitedString<T>(this IEnumerable<T> source) { return source.ToDelimitedString(x => x.ToString(), CultureInfo.CurrentCulture.TextInfo.ListSeparator); } public static string ToDelimitedString<T>( this IEnumerable<T> source, Func<T, string> converter) { return source.ToDelimitedString(converter, CultureInfo.CurrentCulture.TextInfo.ListSeparator); } public static string ToDelimitedString<T>( this IEnumerable<T> source, string separator) { return source.ToDelimitedString(x => x.ToString(), separator); } public static string ToDelimitedString<T>(this IEnumerable<T> source, Func<T, string> converter, string separator) { return string.Join(separator, source.Select(converter).ToArray()); } }... 展开详请

是否可以编写一个模板来检查函数的存在?

梦飞翔758WEB工程师 硬件玩家 CHH不负责版主
我采取了Nicola Bonelli和Johannes Schaub非常有帮助的答案,并将他们合并成一个解决方案,即恕我直言,更具可读性,清晰,不需要typeof扩展: template <class Type> class TypeHasToString { // This type won't compile if the second template parameter isn't of type T, // so I can put a function pointer type in the first parameter and the function // itself in the second thus checking that the function has a specific signature. template <typename T, T> struct TypeCheck; typedef char Yes; typedef long No; // A helper struct to hold the declaration of the function pointer. // Change it if the function signature changes. template <typename T> struct ToString { typedef void (T::*fptr)(); }; template <typename T> static Yes HasToString(TypeCheck< typename ToString<T>::fptr, &T::toString >*); template <typename T> static No HasToString(...); public: static bool const value = (sizeof(HasToString<Type>(0)) == sizeof(Yes)); }; 我用gcc 4.1.2查了一下。信贷主要是尼古拉Bonelli和约翰Schaub,所以给他们一个投票,如果我的回答可以帮助你:)... 展开详请
领券