在foreach中使用ref的替代方法? [英] Alternative to using ref in foreach?

查看:484
本文介绍了在foreach中使用ref的替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有类似签名的修改方法

I have a modifying method with a signature like

private bool Modify(ref MyClass obj);

将修改obj并使用其返回值指示成功. Modify不会重新分配引用(我知道这是行不通的),只是修改实例字段,所以我想使用它来执行以下操作:

that will make modifications to obj and indicate succes with it's return value. Modify is not reassigning the reference (I know that this wouldn't work), just modifying instance fields, so I want to use it to do something like the following:

foreach(MyClass obj in myList)
{
    bool success = Modify(obj);
    // do things depending on success
}

我遇到编译问题,因为obj是未与ref关键字一起传递".但是,如果我这样放置ref关键字:

I am running into a problem compiling as obj is "not being passed with the ref keyword". However, if I put the ref keyword in like so:

bool success = Modify(ref obj);

我得到不能将obj用作ref/out,因为它是一个'foreach迭代变量".我了解到foreach使用了一个不变的迭代器,这就是为什么它不起作用的原因.

I get "cannot use obj as a ref/out because it is a 'foreach iteration variable". I understand that foreach uses an immutable iterator and that's why this doesn't work.

我的问题是使这种工作最简单的替代方法是什么?

My question is what is the easiest alternative to make something like this work?

我尝试使用

foreach(int i = 0; i < myList.Count; i++)
{
    bool success = Modify(ref myList[i]);
    // do things depending on success
}

但是我得到属性或索引器可能不会作为out ref参数传递".

but they I get "a property or indexer may not be passed as an out of ref parameter".

谢谢您的帮助.

推荐答案

您声明

修改未重新分配参考

Modify is not reassigning the reference

因此,Modify(ref MyClass)函数没有理由需要通过ref传递参数.

Therefore, there is no reason the Modify(ref MyClass) function needs to pass argument by ref.

无论是什么(只要澄清一下),您都应该能够进行相同的修改",方法是按值传递对象引用,即删除ref关键字.

You should be able to do the same "modifications", whatever that is (please clarify that) by passing the object reference by value, i.e. removing the ref keyword.

因此,此修补程序应该将您的Modify函数签名从Modify(ref MyClass)更改为Modify(MyClass)

So, the fix here should be changing your Modify function signature from Modify(ref MyClass) to Modify(MyClass)

这篇关于在foreach中使用ref的替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆