如果将foo
强制转换为实现IEnumerable
或dynamic
的类型,则会编译以下代码。有没有一种方法可以在不强制转换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)
{
}
}
答案 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)
{
}
}