c# - C#, overload for single T and for IEnumerable
问题描述
public static void AddOrUpdate<T>(T entry) where T : class
{
//stuff
}
public static void AddOrUpdate<T>(IEnumerable<T> entries) where T : class
{
foreach (var entry in entries)
{
//stuff
}
No matter what I send into this method, the first one is always chosen. How do I separate IEnmuerables and single objects?
AddOrUpdate(entry); //goes into first one
AddOrUpdate(new Analog[] { entry}); //still goes into first one
解决方案
Given that you don't want to change the method declarations at all, there are two ways I can think of to make the compiler prefer the second one when you call the method.
specify the generic parameter:
AddOrUpdate<Analog>(new Analog[] { entry });
make the argument of the compile time type
IEnumerable<Analog>
:IEnumerable<Analog> x = new Analog[] { entry }; AddOrUpdate(x); // or AddOrUpdate(new string[] {""}.AsEnumerable());
推荐阅读
- c# - 如何删除 Windows 凭据
- javascript - ElementHandle 与 DOM 元素有何不同?
- arrays - 根据名称返回单元格的最后两个值
- groovy - 将 RapidMiner ExampleSet 属性转换为 FileObject
- html-table - HTML - 如何避免单元格表中的文本在单元格很短时溢出?
- javascript - REACT 渲染为空
- sql - SQL - 具有不同条件的同一列的总和 - 一个不同,一个不
- facebook-graph-api - Facebook PHP SDK 告诉我我的域不在我的“应用程序域”列表中
- android - 在 Firebase RecyclerView 中添加或删除子项时重复列表行
- python - 如何使用来自另一个 python VM 的模块