c# - 测试列表
问题描述
我正在尝试使用“as”关键字进行测试,但即使我尝试测试的变量是一个集合,也会得到 null。
DoSomething(() => someMethodReturningCollection());
DoSomething(() => anotherMethodReturningAnObject());
public void DoSomething(Func<T> aFunc)
{
var result = aFunc();
var test = result as List<T>;
if(test != null){
DoTaskA();
return;
}
//Here `result` is not a collection
DoTaskB();
}
test
始终为空。节目typeof(T)
另当别论IEnumerable<T>
。
我不认为这是一个重复的问题
,我试图通过使用“as”运算符来测试一个类型是否是一个集合。问题似乎是List<T>
v.List<string>
或List<customer>
. 我可以成功测试result as List<customer>
但不能result as List<T>
。似乎as
操作员需要一个显式类型 - 而不是T
.
解决方案
编辑:由于新的事实,完全改变了答案。
您不能将 T 有时视为 T 有时视为 IEnumerbable。
两种方法
你可以有两种方法
void DoSomething<T>(Func<IEnumerable<T>> aFunc)
{
// Collection code
}
void DoSomething<T>(Func<T> aFunc)
{
// Single code
}
一种方法,非常有限
这是我能做的最好的atm:
DoSomething<string>(() => new[] { "a", "b" });
DoSomething<string>(() => new List<string> { "a", "b" });
DoSomething<string>(() => "c");
void DoSomething<T>(Func<object> aFunc)
{
var result = aFunc();
if (result is IEnumerable<T>)
{
Console.WriteLine("collection!");
return;
}
Console.WriteLine("single!");
}
collection!
collection!
single!
总是一个 IEnumerable
我会让你所有的方法返回 IEnumerable 并打开元素的数量。是的,这是不同的,但可以说更好。
DoSomething(() => new[] { "a", "b" });
DoSomething(() => new List<string> { "a", "b" });
DoSomething(() => new[] { "c" });
void DoSomething<T>(Func<IEnumerable<T>> aFunc)
{
var result = aFunc();
if (!result.Any())
{
Console.WriteLine("empty!");
}
else if (result.Count() > 1)
{
Console.WriteLine("collection!");
} else
{
Console.WriteLine("single!");
}
}
推荐阅读
- java - lambda 处的 JavaFX pane.getChildren().remove() 问题
- c# - 日期在asp.net中的不同时区随机更改
- selenium - 如何在 Selenium Side runner 中传递运行时参数(参数)?
- sql - 查询以返回具有重复出现的字符串/数字的所有记录
- typescript - 如何在 Typescript 中更改 Autodesk Forge Viewer 标记扩展中的编辑模式?
- microsoft-graph-api - MS GraphAPI 在委托模式下支持 Exchange RoomMailBox 上的通知/订阅
- powershell - 无法更新 azure devops 管道上的 powershell 任务版本
- python - Scrapy在爬行时返回无序值
- python - 使用 ResNet50,验证准确度和损失不会改变
- c++ - 模板静态成员定义取决于传递给链接器的顺序