Tos*_*shi 18 c# methods extension-methods
我有一个非常通用的扩展方法来显示控制台中的任何类型的列表:
public static void ShowList<T>(this IEnumerable<T> Values)
{
foreach (T item in Values)
{
Console.WriteLine(item);
}
}
Run Code Online (Sandbox Code Playgroud)
不是我有一个string我可以使用这个方法
string text = "test";
text.ShowList();
Run Code Online (Sandbox Code Playgroud)
但是如果string它在我的应用程序中没有意义.
如何string从这种方法中排除?我读过一些关于
ShowList<T>(this IEnumerable<T> Values): Where != string //doesn't work
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 31
这听起来像是一个奇怪的要求开始,说实话 - 如果某些东西适用于任何字符序列,那么它应该适用于字符串,这是一个字符序列.
如果你真的想让它无法编译,你可以添加一个string标记为过时的重载接受:
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete(IsError = true, Message = "A string is a sequence of characters, but is not intended to be shown as a list")]
public static void ShowList(this string text)
{
throw new NotSupportedException();
}
Run Code Online (Sandbox Code Playgroud)
重载决策将选择该方法,然后它将无法编译.该EditorBrowsable属性有望从Intellisense中删除 - 但你必须看看它是否真的有效.(它可能会显示其他超载,即使不会被选中.)
另一种选择是实现ShowList<T>好像字符串是单条目列表:
// Specialization to avoid listing each character separately.
public static void ShowList(this string text) => new[] { text }.ShowList();
Run Code Online (Sandbox Code Playgroud)
换句话说,让它调用有效,但更适当地处理它.
您可以创建另一个ShowList()特定的重载string并将其标记为[Obsolete]:
[Obsolete("Not intended for strings", true)]
public static void ShowList(this string val)
{
}
Run Code Online (Sandbox Code Playgroud)
通过传递true给IsError参数,编译器将阻止您使用该方法.