首页 / C# / c# – 泛型方法的多个约束?
c# – 泛型方法的多个约束?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 泛型方法的多个约束?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1595字,纯文字阅读大概需要3分钟。
内容图文
![c# – 泛型方法的多个约束?](/upload/InfoBanner/zyjiaocheng/795/c14b8879fdad4f30ad8843dcda7b9c45.jpg)
我有以下四种重载方法Add:
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));
}
有没有办法让第一次和第二次重载成泛型函数?其他一些抽象机制也会有所帮助.
澄清我的意思(这不会编译!):
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# – 泛型方法的多个约束?全部内容,希望文章能够帮你解决c# – 泛型方法的多个约束?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。