如何“做” C# 中的 ByVal

发布于 2024-09-05 15:10:42 字数 152 浏览 11 评论 0原文

据我了解,C# 通过引用将参数传递给方法。在 VB.NET 中,您可以使用 ByVal 和 ByRef 指定这一点。默认为 ByVal。

这是为了与 Visual Basic 6.0 兼容,还是只是随机的?另外,我如何指定在 C# 中使用什么?我有点喜欢按值传递参数的想法。

As I understand it, C# passes parameters into methods by reference. In VB.NET, you can specify this with ByVal and ByRef. The default is ByVal.

Is this for compatibility with Visual Basic 6.0, or is it just random? Also, how can I specify what to use in C#? I kind of like the idea of passing parameters by value.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

随风而去 2024-09-12 15:10:42

C# 中的参数默认是按值传递的。没有修饰符可以使其明确,但如果添加 ref / out 则参数是按引用的。

这里常见的混淆是以下两者之间的区别:

  • 按值传递值类型(调用者看不到对值类型的更改,但理想情况下值类型无论如何应该是不可变的)
  • 按引用传递值类型(更改为值类型对调用者来说是可见的,但值类型在理想情况下应该是不可变的 - 非常重要,我会说两次;p)
  • 按值传递引用(更改为字段/属性引用类型对调用者可见,但重新分配引用类型到新的/不同的对象可见)
  • 通过引用传递引用(更改字段/属性,重新分配引用对调用者可见)

Parameters in C# are, by default passed by value. There is no modifier to make this explicit, but if you add ref / out the parameter is 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)
  • 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)
  • passing a reference by reference (changes to fields/properties, and reassigning the reference are visible to the caller)
如此安好 2024-09-12 15:10:42

按值传递是 C# 中的默认设置。但是,如果传递的变量是引用类型,那么您将按值传递引用。这或许就是你困惑的根源。

基本上,如果您按值传递引用,那么您可以更改它引用的对象,并且这些更改将在方法外部持续存在,但是您不能使变量引用不同的对象并使该更改在方法外部持续存在。

Passing by value is the default in 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.

阳光的暖冬 2024-09-12 15:10:42

C# 中的参数默认通过“ByVal”传递。如果您想要不同的行为,则必须指定“ref”或“out”。

Parameters in C# are passed "ByVal" by default. You have to specify "ref" or "out" if you want different behavior.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文