gpt4 book ai didi

c# - 'T' 不包含 'Foo' 的定义,最佳扩展方法重载需要类型为 'IType' 的接收器

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:25 25 4
gpt4 key购买 nike

我有这样的代码:

using System;
using System.Collections.Generic;
using System.Linq;

public interface IMyString
{
string Id {get;set;}
};

public class MyString : IMyString
{
public string Id {get;set;}
}

public static class Extensions
{
public static IEnumerable<IMyString> WithId(this IEnumerable<IMyString> source, string id)
{
return source.Where(x => x.Id == id);
}
}

public class Program
{
private static List<T> GetMyStrings<T>(string key, List<T> input)
where T: IMyString
{
return input.WithId(key).ToList();
}

public static void Main()
{
var foo = new List<MyString>{ new MyString { Id = "yes"}, new MyString { Id = "no" } };
var result = GetMyStrings("yes", foo);
var result2 = foo.WithId("no");
Console.WriteLine(result2);
}
}

为什么 input.WithId(key).ToList() 导致语法错误,而 foo.WithId("no") 没问题?有没有办法使方法 GetMyStrings 起作用?

最佳答案

如果没有代码的上下文,提供太多帮助有点困难,但是这两种方法的类型约束是不同的。您有两个选择:

选项 1:

public static class Extensions
{
public static IEnumerable<T> WithId<T>(this IEnumerable<T> source, string id) where T: IMyString
{
return source.Where(x => x.Id == id);
}
}

选项 2:

private static List<IMyString> GetMyStrings(string key, List<IMyString> input)
{
return input.WithId(key).ToList();
}

public static void Main()
{
var foo = new List<IMyString>{ new MyString { Id = "yes"}, new MyString { Id = "no" } };
var result = GetMyStrings("yes", foo);
var result2 = foo.WithId("no");
Console.WriteLine(result2);
}

这是一个dotnetfiddle将第二个选项作为工作代码:

关于c# - 'T' 不包含 'Foo' 的定义,最佳扩展方法重载需要类型为 'IType' 的接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58694628/

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