我有一个从因特网下载的IEnumerable扩展方法,我正在努力编写一个有效的回顾性测试。
可拓方法
public static bool In<T>(this T source, params T[] list) where T : IEnumerable
{
if (source == null) throw new ArgumentNullException("source");
return list.Contains(source);
}
测试
[TestMethod]
public void In()
{
IEnumerable<int> search = new int[] { 0 };
IEnumerable<int> found = new int[] { 0, 0, 1, 2, 3 };
IEnumerable<int> notFound = new int[] { 1, 5, 6, 7, 8 };
Assert.IsTrue(search.In(found));
Assert.IsFalse(search.In(notFound));
}
结果
所有代码都会编译,但是在这两个断言中,当我认为第一个断言search.In(found)
应该返回true时,扩展方法的结果返回false。
问题
我是在调用代码中做错了什么,还是扩展名出现了问题?
发布于 2013-09-18 12:13:17
要运行此测试,应该如下所示:
[TestMethod]
public void In()
{
IEnumerable<int> search = new int[] { 0 };
IEnumerable<int> a = new int[] { 0, 0, 1, 2, 3 };
IEnumerable<int> b = new int[] { 0, 0, 1, 2, 3 };
IEnumerable<int> c = new int[] { 0};
Assert.IsTrue(search.In(a,b,c));
Assert.IsFalse(search.In(a,b));
}
这是因为您在这里搜索的是整组int,而不是其中的项目。
在上面的代码中,您正在检查在所有传递的参数中是否存在您正在搜索的数组。
如果您想要在列表中包含检查是否项的扩展名,请尝试如下:
public static bool In<T> (this T value, IEnumerable<T> list)
{
return list.Contains(value);
}
然后你就可以:
[TestMethod]
public void In()
{
IEnumerable<int> search = 0;
IEnumerable<int> found = new int[] { 0, 0, 1, 2, 3 };
IEnumerable<int> notFound = new int[] { 1, 5, 6, 7, 8 };
Assert.IsTrue(search.In(found));
Assert.IsFalse(search.In(notFound));
}
编辑:
谢谢您对Marcin的评论
发布于 2013-09-18 12:13:25
你的T
是IEnumerable<int>
,而不是int
。将局部变量键入为int[]
。现在,您正在使用params参数槽中的单个IEnumerable<int>
调用IEnumerable<int>
。
再看一看,你那里的分机是假的。为什么源项和搜索项( params参数)都应该是IEnumerable
?没有任何意义。以下是一个工作版本:
public static bool In<T>(this T operand, params T[] values) where T : IEquatable<T>
{
if (values == null) throw new ArgumentNullException("operand");
return In(operand, ((IEnumerable<T>)values));
}
public static bool In<T>(this T operand, IEnumerable<T> values) where T : IEquatable<T>
{
if (values == null) throw new ArgumentNullException("operand");
return values.Contains(operand);
}
发布于 2013-09-18 12:24:21
如果您想检查天气,source
中的所有元素都在list
中
public static bool In<T>(this IEnumerable<T> source, IEnumerable<T> list)
{
if (source == null) throw new ArgumentNullException("source");
return source.All(e => list.Contains(e));
}
IEnumerable<int> search = new int[] { 0 };
IEnumerable<int> found = new int[] { 0, 0, 1, 2, 3 };
IEnumerable<int> notFound = new int[] { 1, 5, 6, 7, 8 };
Console.WriteLine(search.In(found));//True
Console.WriteLine(search.In(notFound));//False
https://stackoverflow.com/questions/18871905
复制相似问题