C# 列表测试<;T>;
我尝试使用'as'关键字进行测试,但即使我尝试测试的变量是一个集合,也会得到nullC# 列表测试<;T>;,c#,generics,C#,Generics,我尝试使用'as'关键字进行测试,但即使我尝试测试的变量是一个集合,也会得到null DoSomething(() => someMethodReturningCollection()); DoSomething(() => anotherMethodReturningAnObject()); public void DoSomething(Func<T> aFunc) { var result = aFunc(); var test = result a
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();
}
DoSomething(()=>someMethodReturningCollection());
DoSomething(()=>anothermethodreurninganobject());
公共无效剂量测定(Func aFunc)
{
var result=aFunc();
var测试=结果列表;
如果(测试!=null){
DoTaskA();
返回;
}
//这里的'result'不是一个集合
DoTaskB();
}
测试始终为空。typeof(T)
显示为IEnumerable
否则
我不认为这是一个重复的问题
我试图通过使用'as'操作符来测试类型是否为集合。问题似乎是列表
v<代码>列表
或列表
。我可以成功地将结果测试为列表
,但不能将结果测试为列表
。似乎as
操作符需要一个显式类型,而不是T
编辑:由于新的事实,答案完全改变了
你不能把T有时当作T,有时当作i不可数
两种方法
你可以有两种方法
void DoSomething<T>(Func<IEnumerable<T>> aFunc)
{
// Collection code
}
void DoSomething<T>(Func<T> aFunc)
{
// Single code
}
总是数不清的
我会让所有方法返回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!");
}
}
DoSomething(()=>new[]{“a”,“b”});
DoSomething(()=>新列表{“a”,“b”});
DoSomething(()=>new[]{“c”});
无效剂量测定(Func aFunc)
{
var result=aFunc();
如果(!result.Any())
{
控制台。WriteLine(“空!”);
}
else if(result.Count()>1)
{
Console.WriteLine(“collection!”);
}否则
{
控制台。WriteLine(“单条!”);
}
}
那么,什么样的收藏?result.GetType()说“否则,类型(T)显示为IEnumerable”-IEnumerable
与List
完全不同。如果as
返回null
,则该对象不是您要求的目标类型。就这么简单。有关两者之间区别的详细信息,请参见duplicate。从其他注释中可以看出:“aFunc可以返回集合或单个对象。”。test
用于什么?@tymtam:原来的问题是重复的。把实际问题改成不同的东西是不合法的,特别是如果你不是问题的真正作者的话。如果你想回答一个不同的问题,请继续并张贴该问题,并将答案放在那里。不要编辑现有的问题使它们不同。不,我不会转换。我正在测试结果是否为列表或集合。作为列表的结果不为空。当我使用T
时,它总是返回null。运行时的typeof(T)是一个IEnumerable,因此我不确定编译器为什么使用实际的type list结果作为list
和test/convert.BTW。它是IEnumerable
还是IEnumerable
?这些是不同的类型。IEnumerable。aFunc可以返回集合或单个对象。使用Func
,我已经知道返回类型是一个集合,因此无需测试集合。您传入的示例方法的签名是什么?DoSomething(()=>someMethodReturningCollection())
和DoSomething(()=>anotherMethodReturningSingleObject())
collection!
collection!
single!
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!");
}
}