如何“做” C# 中的 ByVal
据我了解,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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C# 中的参数默认是按值传递的。没有修饰符可以使其明确,但如果添加
ref
/out
则参数是按引用的。这里常见的混淆是以下两者之间的区别:
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:
按值传递是 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.
C# 中的参数默认通过“ByVal”传递。如果您想要不同的行为,则必须指定“ref”或“out”。
Parameters in C# are passed "ByVal" by default. You have to specify "ref" or "out" if you want different behavior.