c# - 泛型方法的多重约束?

标签 c# generics ienumerable

我有以下四个方法重载:

    public IEnumerable<TrackInfo> Add(DataContext dataContext, IEnumerable<TrackInfo> tracks)
    {
        return tracks.Select(t => Add(dataContext, t));
    }

    public IEnumerable<TrackInfo> Add(DataContext dataContext, IEnumerable<string> files)
    {
        return files.Select(f => Add(dataContext, f));
    }

    public TrackInfo Add(DataContext dataContext, TrackInfo track)
    {
        dataContext.TrackInfos.InsertOnSubmit(track);
        Add(track);
        return track;
    }

    public TrackInfo Add(DataContext dataContext, string path)
    {
        return Add(dataContext, new TrackInfo(path));
    }

有没有什么办法可以让 first 和 second 重载成为泛型函数?其他一些抽象机制也会有所帮助。

澄清我的意思(这不会编译!):

public IEnumerable<TrackInfo> Add<T>(DataContext dataContext, IEnumerable<T> items) where T : TrackInfo, string
{
    return items.Select(i => Add(dataContext, i));
}

首先,我不能使用字符串作为约束,因为它是密封的。其次,我不认为我可以通过这种方式指定多个约束。有什么解决办法吗?

最佳答案

不是最佳答案,但我认为这可能是您想要的:

public IEnumerable<TrackInfo> Add<T>(DataContext dataContext, IEnumerable<T> tracks) where T : class
{
    if(typeof(T) == typeof(string)) 
    {
        return tracks.Select(t => Add(dataContext, new TrackInfo(t)));
    }
    else if(typeof(T) == typeof(TrackInfo)) 
    {
        return tracks.Select(t => Add(dataContext, t as TrackInfo));
    }
    else 
    {
        throw new ArgumentException("The type must be string or TrackInfo");
    }
}

public TrackInfo Add(DataContext dataContext, TrackInfo track)
{
    dataContext.TrackInfos.InsertOnSubmit(track);
    Add(track);
    return track;
}

// you may not need this
public TrackInfo Add(DataContext dataContext, string path)
{
    return Add(dataContext, new TrackInfo(path));
}

关于c# - 泛型方法的多重约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30495064/

相关文章:

c# - 从一个位置调用多个 ASP.Net Core 微服务

c# - 使用 Linq 在 C# 泛型列表中查找最新项

Java 接口(interface)泛型,返回类型取决于参数泛型

delphi - 是否可以为泛型类创建类型别名

c# - Dispose 与 Iterator block

c# - 使用控制台应用程序进行 ADFS STS 身份验证

c# - 如何获取 Sql Server 数据库中所有模式的列表

c# - 是否可以在 C# 中将执行命令存储在列表中并在循环中执行

c# - IEnumerable 属性的 ValidationAttribute

c# - IQueryable 和 IEnumerable 之间区别的真实示例?