【发布时间】:2011-05-14 06:43:06
【问题描述】:
我正在做一个 AOP 类型的层,我想返回一个通用集合的迭代器块(即类似“IEnumerable”的东西)。但是,类型 T 是动态发现的。我可以找到该类型并将其作为“类型”变量在本地使用,但我如何超越该类型并为该动态发现的类型返回一个迭代器块?
我想要的是这样的(尽可能用传统 C# 表达):
public IEnumerator<runtimeDiscoveredType> EntryIteratorBlock(Type desiredElementType)
{
// One can assume that desireElementType is the same as (or convertible to) runtimeDiscoveredType
TypeConverter tc = new TypeConverter()
var actualItem = ....; // some code goes here to pick up the actual item from
... // some collection.
if (ChooseThisItem(actualItem))
yield return tc.ConvertTo(actualItem, desiredElementType);
else
yield break;
}
然后我想返回 EntryIteratorBlock 以便我可以动态地遍历集合。 (集合中的元素加载起来很昂贵,所以我想懒惰地加载它们。)
【问题讨论】:
-
我同意彼得的观点;一个更具体的例子会让你更容易判断我是否在写你正在尝试做的事情。