想知道为什么这个不起作用。非常感谢您的帮助。
static void Main(string[] args)
{
List<int> foo = new List<int> { 1, 2, 3 };
var myResult = MyTest<int>(foo);
}
private static List<int> MyTest<T>(List<T> input)
{
List<int> bar = new List<int> { 2, 3, 4 };
return bar.Where(b => input.Contains(b)).ToList();
}
MyTest()函数的预期输出是一个列表{2, 3}。然而,在处,编译器报告了两个错误,分别是:
参数1:无法将'int'转换为'T'
System.Collections.Generic.List.Contains(T)的最佳重载方法具有一些无效的参数
这只是我的实际问题的简化,所以请不要卡在“为什么要写这个?”上。问题是错误及其发生原因。
namespace SandBox
{
class Foo
{
public int FooInt { get; set; }
public string FooString { get; set; }
}
class Program
{
private static List<Foo> fooList = new List<Foo> {
new Foo() {FooInt = 1, FooString = "A"},
new Foo() {FooInt = 2, FooString = "B"},
new Foo() {FooInt = 3, FooString = "C"}
};
static void Main(string[] args)
{
List<int> myIntList = new List<int> { 1, 2 };
var myFirstResult = GetFoos<int>(myIntList);
List<string> myStringList = new List<string> { "A", "B" };
var mySecondResult = GetFoos<string>(myStringList);
}
/// <summary>
/// Return a list of Foo objects that match the input parameter list
/// </summary>
private static List<Foo> GetFoos<T>(List<T> input)
{
//***
// Imagine lots of code here that I don't want to duplicate in
// an overload of GetFoos()
//***
if (input is List<int>)
{
//Use this statement if a list of integer values was passed in
return fooList.Where(f => input.Contains(f.FooInt));
}
else if (input is List<string>)
{
//Use this statement if a list of string values was passed in
return fooList.Where(f => input.Contains(f.FooString));
}
else
return null;
}
}
}
相同的编译器错误会在
input.Contains(f.Property)
上报告。
input
是List<int>
,为什么你要使用<T>
? - Austin Salonenreturn bar.Intersect(input);
会更高效。 - Tim SchmelterMyTest<string>(someStrings)
。 - Sergey Berezovskiy