c# - 如果 T 是 IEnumerable 而没有强制转换,则遍历泛型类型 T
问题描述
如果将以下代码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)
{
}
}
解决方案
我不太确定你不想投稿的原因是什么,但这样的事情对你有用吗?
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)
{
}
}
推荐阅读
- javascript - Vue 动态 xlink:href attr
- c - 函数类型的左值是否是可修改的左值?
- python - 如何在 Python 中为 0.1 步构建计时器
- fonts - SwiftUI:如何在 NavBarTitle 中获取 .serif(纽约)字体
- groovy - 在列表中查找具有相同最后一个字母的元素
- php - 如何对包含 php 文件进行正确的错误处理
- c# - 数据为空。不能对 Null 值调用此方法或属性。实体框架核心
- java - 如何使用其他相关表的 id 引用添加记录?
- node.js - 带有 TypeScript 的 JQuery 的 Kendo UI
- android - 改造错误 - Android Studio 中的状态码 34