泛型类中的 c# 方法仅适用于某些类型

标签 c# generics

我正在尝试在仅限于特定类型的泛型类上定义一个方法。我想出了这个:

interface IHasId 
{
    int Id { get; }
}

public class Foo<T>
{
    private List<T> children;

    public IHasId GetById(int id)
    {
        foreach (var child in children.Cast<IHasId>())
        {
            if (child.Id == id)
            {
                return child;
            }
        }

        return null;
    }
}

它会工作,但它看起来像代码味道......似乎应该有一种方法让编译器强制执行此操作。像这样的东西:

public class Foo<T>
{
    public IHasId GetById<TWithId>(int id) where TWithId : IHasId {}
}

或者,甚至更好:

public class Foo<T>
{
    public IHasId GetById(int id) where T : IHasId {}
}

我看到一些与 Java 相关的帖子,其中一篇专门讨论将 T 限制为枚举,但没有直接切入点。

最佳答案

你不能有基于单一类型的可选方法。但是,您可以使用继承来使其发挥作用。

方法如下:

public interface IHasId 
{
    int Id { get; }
}

public class Foo<T>
{
    protected List<T> children;
}

public class FooHasId<T> : Foo<T> where T : IHasId
{
    public IHasId GetById(int id)
    {
        foreach (var child in children)
        {
            if (child.Id == id)
            {
                return child;
            }
        }
        return null;
    }
}

使用 C#6 FooHasId 可以缩短为:

public class FooHasId<T> : Foo<T> where T : IHasId
{
    public IHasId GetById(int id) => this.children.FirstOrDefault(x => x.Id == id);
}

关于泛型类中的 c# 方法仅适用于某些类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44233004/

相关文章:

c++ - 默认参数和泛型类

c# - .net 框架中的集合 <T> 类位置

c# - 在 C# 2.0 .net 中使用 Type.GetType(string) 但找不到类型或命名空间名称 't'

java - 如何制作泛型的构造函数

java - 列表初始化的奇怪错误

c# - 为项目列表选择正确的控件

java - 转换为在运行时确定的类

c# - 如何使用 LINQ 从一组数字中查找 n 项的所有组合?

c# - 在没有打开 Outlook 应用程序的情况下阅读电子邮件

javascript - JQuery DataTable设置默认空搜索Echo参数