gpt4 book ai didi

c# - LINQ 查询中的 List.Contains(T) 出错

转载 作者:太空狗 更新时间:2023-10-30 01:07:09 25 4
gpt4 key购买 nike

想知道为什么这不起作用。洞察力赞赏。

    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 }。但是编译器在input.Contains(b)上报了两个错误,如下:

  1. 参数 1:无法从“int”转换为“T”

  2. “System.Collections.Generic.List.Contains(T)”的最佳重载方法匹配有一些无效参数

如果我不使用通用列表,这个 Where() 子句工作正常。

这是对我的现实问题的简化,所以请不要纠结于“你为什么要写这个?”问题是错误及其发生的原因。

为(希望)清楚起见进行了修订:

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不是一个 int,你会知道它总是返回一个空列表。

T 时,该函数没有多大意义。不是一个整数。

关于c# - LINQ 查询中的 List<T>.Contains(T) 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13368973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com