如何将一个方法的值传递给另一个方法 [英] How to pass the value of one method to another

查看:57
本文介绍了如何将一个方法的值传递给另一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我的方法是

Hi all,

I have a method which is

int x = 0; 
string a = string.Empty; 
string b = string.Empty;
MyMethod(x, a, b);





现在这个方法将修改a和b的值。如果这是可能的,那么为什么我们需要ref关键字?或者这个功能只在最新的C#4.0中?



谢谢,

Ankita



Now this method will modify the values of a and b. If this is possible then why do we need ref keyword? Or this feature is only in latest C# 4.0?

Thanks,
Ankita

推荐答案

引用参数不传递函数成员调用中使用的变量的值 - 它们使用变量本身。不是在函数成员声明中为变量创建新的存储位置,而是使用相同的存储位置,因此函数成员中的变量值和引用参数的值将始终相同。引用参数需要ref修饰符作为声明和调用的一部分。
Reference parameters don't pass the values of the variables used in the function member invocation - they use the variables themselves. Rather than creating a new storage location for the variable in the function member declaration, the same storage location is used, so the value of the variable in the function member and the value of the reference parameter will always be the same. Reference parameters need the ref modifier as part of both the declaration and the invocation .


原始数据类型按值传递。

因此,如果您更改值方法中的这些变量,调用者值不会受到影响。



为了确保这些变量的值在调用者和被调用者之间发生变化,你可以使用 byRef

此功能适用于所有版本。
Primitive data types are passed by value.
Thus if you change the value of these variables inside the method, the caller values will not be affected.

To ensure the values of these variables change across the caller and the called, you can use byRef.
This feature is available in all versions.


首先,如果你想要变量'a并且'b要在方法中修改,你不必通过它们!这两个变量在方法的范围之外声明,因此在方法中对它们进行的任何更改都将持久地在方法之外。



通过引用传递参数是程序员工具箱的重要部分,您应该完全理解它。在C#中你需要练习使用'ref和'out修饰符来参数,并理解它们之间的区别。



'ref和'out都可以通过以下方式传递值或对象reference:'out不要求传递的引用被初始化,'ref要求它被初始化。在传递之前使用'out'为传递的值赋值将导致编译时错误。



我建议你仔细研究Jon Skeet的这些文章:[ ^ ],[ ^ ]。如果它们令人困惑......现在对你来说太先进了......然后试试Charles Petzold的书Dot Net Zero(免费):[ ^ ]。
First of all, if you want variables 'a and 'b to be modified in the method, you don't have to pass them ! The two variables are declared outside the scope of the method, therefore any change made to them in the method will persist "outside" the method.

Passing parameters by reference is an important part of the programmer's toolbox, and you should fully understand it. In C# you need to practice using both 'ref and 'out modifiers to parameters, and understand the difference.

Both 'ref and 'out enable passing values or objects by reference: 'out does not require the passed reference to be initialized, and 'ref requires it be initialized. Assigning a value to the variable to passed using 'out before it is passed will result in a compile time error.

I suggest you study these articles by Jon Skeet very carefully: [^], [^]. If they are confusing ... too advanced for you right now ... then try Charles Petzold's book "Dot Net Zero" (free): [^].


这篇关于如何将一个方法的值传递给另一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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