【发布时间】:2018-03-02 15:16:00
【问题描述】:
我遇到了一些简单的 C# 代码问题,我可以在 C/C++ 中轻松修复。 我想我错过了一些东西。
我想做以下事情(修改列表中的项目——就地):
//pseudocode
void modify<T>(List<T> a) {
foreach(var item in a) {
if(condition(item)) {
item = somethingElse;
}
}
}
我知道 foreach 循环在一个被视为不可变的集合上,所以上面的代码不能工作。
因此我尝试了以下方法:
void modify<T>(List<T> a) {
using (var sequenceEnum = a.GetEnumerator())
{
while (sequenceEnum.MoveNext())
{
var m = sequenceEnum.Current;
if(condition(m)) {
sequenceEnum.Current = somethingElse;
}
}
}
}
天真地认为 Enumerator 是某种指向我的元素的指针。显然枚举数也是不可变的。
在 C++ 中我会这样写:
template<typename T>
struct Node {
T* value;
Node* next;
}
然后能够修改 *value 而不触及 Node 中的任何内容,因此在父集合中:
Node<T>* current = a->head;
while(current != nullptr) {
if(condition(current->value))
current->value = ...
}
current = current->next;
}
我真的需要不安全的代码吗?
还是我在循环中陷入了调用下标的可怕问题?
【问题讨论】:
-
“任何一个 C# 都有严重的问题” - 你知道有多少人使用 C#?你真的认为如果这种语言存在严重问题,它会是目前最受欢迎的语言之一吗?退后一步考虑一下。问题更可能出在您身上,而不是语言上。
-
好的,我从我的问题中删除了我的幽默
-
使用
for循环有什么问题? -
和 C,因为我添加了模板
-
(properties) modified & set default(null in the case of reference types)是一个非常不同的东西。提出正确的问题,您将得到准确的答案。
标签: c# list enumerator