首页 > 解决方案 > 测试列表

问题描述

我正在尝试使用“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.

标签: c#generics

解决方案


编辑:由于新的事实,完全改变了答案。

您不能将 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!");
    }
}

推荐阅读