如果T是IEnumerable而无需强制转换,则遍历泛型T

时间:2019-02-13 18:51:45

标签: c# generics casting

如果将foo强制转换为实现IEnumerabledynamic的类型,则会编译以下代码。有没有一种方法可以在不强制转换foo的情况下达到相同的目的? 我知道我可以做两种方法,也不想对T施加更多的约束。

interface IDummy
{}

class FooBar<T> where T : class
{
    void Bar(T foo)
    {
       if (foo is IEnumerable<IDummy>)
          foreach (var item in foo)
             B(item);
       else if(foo is IDummy)
          B(foo);                      
    }  

    void B(IDummy item)
    {

    }
}

1 个答案:

答案 0 :(得分:0)

我不太确定您不愿意投稿的原因是什么,但是这样的事情对您有用吗?

interface IDummy
{}

class FooBar<T> where T : class
{
    void Bar(T foo)
    {
       if (foo is IEnumerable<IDummy> enumerableFoo)
          foreach (var item in enumerableFoo)
             B(item);
       else if(foo is IDummy)
          B(foo);                      
    }  

    void B(T item)
    {

    }
}