不考虑任何理智的理由这样做,简单地出于好奇 是否有可能采取任何给定的IEnumerable(T),并覆盖包含的项?例如,给定一个IEnuemrable(字符串),才有可能彻底了IEnumerable之内更换所有字符串?
Disregarding any sane reason to do this, and simply out of curiosity Is it possible to take any given IEnumerable(T) and overwrite the contained items? For example, given an IEnuemrable(String) is it possible to completely replace all strings within the IEnumerable?
推荐答案至于其他人说,如果IEnumerable的是具体的东西就像一个列表或集合,集合等,那么你可以做到这一点没有反思 - 只投它的类型和惹它。
As other people have said, if the IEnumerable is something concrete like a List or a Collection, Set, etc, then you can do this without reflection - just cast it to that type and mess with it.
如果将IEnumerable的使用迭代器生成的,如:
What if the IEnumerable is generated using an iterator, eg:
public IEnumerable<int> EvenNumbers { get { int i = 2; while (true) { yield return i; i += 2; } } }
你怎么能达到这个并更换一些价值?没有值,以取代 - 下一个值来自循环的下一个评价。有此可枚举在内存中没有全面评估的任何地方,你必须不断地问下一个值,直到你得到你所期待的。
How could you reach into this and replace some value? There are no values to replace - the next value comes from the next evaluation of the loop. There's no full evaluation of this Enumerable in memory anywhere, you have to keep asking for the next value until you get what you were looking for.
所以,不,你不能保证你能挖掘并修改基础值,因为有时没有基本值的所有IEnumerables。
So no, you can't guarantee that for all IEnumerables you can dig in and modify the underlying values because sometimes there are no underlying values.
更多推荐
能够覆盖的IEnumerable&LT项目; T&GT;使用反射?
发布评论