【问题标题】:Test for List<T> [duplicate]测试 List<T> [重复]
【发布时间】:2021-04-07 22:31:49
【问题描述】:

我正在尝试使用“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&lt;T&gt; 否则。

我不认为这是一个重复的问题 我正在尝试使用“as”运算符来测试一个类型是否是一个集合。问题似乎是List&lt;T&gt;List&lt;string&gt;List&lt;customer&gt;。我可以成功测试result as List&lt;customer&gt;,但不能成功测试result as List&lt;T&gt;as 运算符似乎需要一个显式类型 - 而不是 T

【问题讨论】:

  • 嗯,什么样的收藏? result.GetType() 说什么
  • “否则 typeof(T) 显示为 IEnumerable” -- IEnumerable&lt;T&gt;List&lt;T&gt; 完全不同。如果as 返回null,则说明对象不是您要求的目标类型。 就这么简单。有关两者之间区别的详细信息,请参阅副本。
  • 来自其他 cmets:“aFunc 可以返回一个集合或单个对象。”。 test 是干什么用的?
  • @tymtam:原来的问题是重复的。将实际问题更改为不同的东西是不合法的,特别是如果您首先不是问题的实际作者。如果您想回答不同的问题,请继续发布该问题并将您的答案放在那里。不要编辑现有问题以使其与众不同。

标签: c# generics


【解决方案1】:

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

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

【讨论】:

  • 不,我没有转换。我正在测试result 是列表还是集合。 result as List&lt;aType&gt; 不为空。当我使用T 时,它总是返回null。运行时的 typeof(T) 是一个 IEnumerable 所以我不确定为什么编译器使用实际类型列表result as List&lt;replace T with the actual type&gt; 和测试/转换。
  • 顺便说一句。是IEnumerable 还是IEnumerable&lt;T&gt;?这些是不同的类型。
  • IEnumerable。 aFunc 可以返回一个集合或单个对象。使用Func&lt;IEnumerable&lt;T&gt;&gt;,我已经知道返回类型是一个集合,因此无需测试集合。
  • 你传入的示例方法的签名是什么?
  • DoSomething( () =&gt; someMethodReturningCollection() )DoSomething( () =&gt; anotherMethodReturningSingleObject())
猜你喜欢
  • 1970-01-01
  • 2011-08-17
  • 2018-02-13
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 1970-01-01
  • 2010-09-30
  • 1970-01-01
相关资源
最近更新 更多