你需要的ref或out参数? [英] do you need the ref or out parameter?

查看:111
本文介绍了你需要的ref或out参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递一个类的实例的方法,而该方法将修改实例。



我是否需要使用out或ref关键字,因为这?是一类我传递



这是我想做的事:

 公共无效布拉赫()
{
胡说b = Dao.GetBlah(23);

SomeService.ModifyXml(二); //我需要使用out或ref在这里?

Dao.SaveXml(b.xml);

}


解决方案

右的方式来思考是这样的:使用REF /输出,当你想创建一个别名给一个变量。也就是说,当你说:

 无效M(REF INT X){X = 10; } 
...
INT Q = 123;
M(REF Q);



你说的是x是变量q的另一个名字。任何更改为x变化q的内容,然后为q的变化x的内容进行任何更改,因为x和q是对的完全一样的存储位置的只是两个人的名字。



请注意,这是从两个变量引用同一个对象完全不同的:

 对象Y =你好; 
对象Z =ÿ;



在这里,我们的两个变量的,每个变量的一个名字的,每个变量是指的一个对象的,这两个变量都引用的同一个对象的。与前面的例子中,我们只的一个变量的用的两个名字的。



清楚了吗?


I am passing a instance of a class to a method, and that method will modify the instance.

Do I need to use the out or ref keyword since this is a class I am passing?

This is what I want to do:

public void Blah()
{
   Blah b = Dao.GetBlah(23);

   SomeService.ModifyXml(b);    // do I need to use out or ref here?

   Dao.SaveXml(b.xml);

}

解决方案

The right way to think about this is: use ref/out when you want to create an alias to a variable. That is, when you say:

void M(ref int x) { x = 10; }
...
int q = 123;
M(ref q);

what you are saying is "x is another name for the variable q". Any changes to the contents of x change q, and any changes to the contents of q change x, because x and q are just two names for the exact same storage location.

Notice that this is completely different from two variables referring to the same object:

object y = "hello";
object z = y;

Here we have two variables, each variable has one name, each variable refers to one object, and the two variables both refer to the same object. With the previous example, we have only one variable with two names.

Is that clear?

这篇关于你需要的ref或out参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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