首页 > 解决方案 > 如果 T 是 IEnumerable 而没有强制转换,则遍历泛型类型 T

问题描述

如果将以下代码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)
    {

    }
}

标签: c#genericscasting

解决方案


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

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)
    {

    }
}

推荐阅读