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

Sto*_*orm 1 .net c# .net-core

我有这样的代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

pei*_*ent 5

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

选项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);
    }
}
Run Code Online (Sandbox Code Playgroud)

选项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);
}
Run Code Online (Sandbox Code Playgroud)

这是一个dotnetfiddle,其中第二个选项是一段有效的代码: