[英]How to 'do' ByVal in C#
As I understand it, C# passes parameters into methods by reference. 据我了解,C#通过引用将参数传递给方法。 In VB.NET, you can specify this with ByVal and ByRef. 在VB.NET中,您可以使用ByVal和ByRef指定它。 The default is ByVal. 默认为ByVal。
Is this for compatibility with Visual Basic 6.0, or is it just random? 这是为了与Visual Basic 6.0兼容,还是随机的? Also, how can I specify what to use in C#? 另外,如何指定在C#中使用的内容? I kind of like the idea of passing parameters by value. 我有点像按值传递参数的想法。
Parameters in C# are, by default passed by value. 默认情况下 ,C#中的参数按值传递。 There is no modifier to make this explicit, but if you add ref
/ out
the parameter is by-reference. 没有修饰符可以使其显式化,但如果添加ref
/ out
则参数为by-reference。
The usual confusion here is the difference between: 这里通常的混淆是:
Passing by value is the default in C#. 传递值是C#中的默认值。 However, if the variable being passed is of reference type, then you are passing the reference by value. 但是,如果传递的变量是引用类型,那么您将按值传递引用 。 This is perhaps the origin of your confusion. 这可能是你困惑的根源。
Basically, if you pass a reference by value, then you can change the object it refers to and these changes will persist outside the method, but you can't make variable refer to a different object and have that change persist outside the method. 基本上,如果按值传递引用,则可以更改它引用的对象,并且这些更改将保留在方法之外,但是您不能使变量引用另一个对象并使该更改在方法之外保留。
Parameters in C# are passed "ByVal" by default. 默认情况下,C#中的参数传递“ByVal”。 You have to specify "ref" or "out" if you want different behavior. 如果您想要不同的行为,则必须指定“ref”或“out”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.