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

标签 c# .net .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);
    }
}

为什么 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/

相关文章:

c# - html.raw 未呈现

c# - 显示窗口 15 分钟后崩溃

c# - 如何在单例中使用作用域依赖注入(inject)

c# - 为什么 int 属性的 IsValueType 为 false?

asp.net-mvc - Asp.net core MVC post 参数始终为空

c# - 如何在 conversionType 为可为空的 int 时使用 Convert.ChangeType()

c# - WPF 页面如何保存在内存中?

c# - 继续获取 'The LINQ expression node type ' Invoke' 在 LINQ to Entities 的异常中不受支持

c# - 通过输入参数减少表达式

c# - .net 请求浏览器版本不一致