简体   繁体   English

如何在C#中“做”ByVal

[英]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 a value-type by value (changes to the value-type are not visible to the caller, but value-types should ideally be immutable anyway) 按值传递值类型(调用者看不到值类型的更改,但理想情况下值类型应该是不可变的)
  • passing a value-type by reference (changes to the value-type are visible to the caller, but value-types should ideally be immutable anyway - so important I'll say it twice ;p) 通过引用传递值类型(对值类型的更改对调用者是可见的,但值类型理想情况下应该是不可变的 - 所以重要的是我会说两次; p)
  • passing a reference by value (changes to fields/properties of the ref-type are visible to the caller, but reassigning the ref-type to a new/different object is not visible) 通过值传递引用(对于调用者可以看到对ref类型的字段/属性的更改,但是 ref-type 重新分配给新的/不同的对象是可见的)
  • passing a reference by reference (changes to fields/properties, and reassigning the reference are visible to the caller) 通过引用传递引用(更改为字段/属性, 重新分配引用对调用者可见)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM