Are structs 'pass-by-value'?

前端 未结 9 1348
轮回少年
轮回少年 2020-11-30 23:43

I\'ve recently tried to create a property for a Vector2 field, just to realize that it doesn\'t work as intended.

public Vector2 Position { get;         


        
9条回答
  •  暖寄归人
    2020-12-01 00:03

    Yes, structs inherit from ValueType, and are passed by value. This is true for primitive types as well - int, double, bool, etc (but not string). Strings, arrays and all classes are reference types, and are passed by reference.

    If you want to pass a struct by ref, using the ref keyword:

    public void MyMethod (ref Vector2 position)
    

    which will pass the struct by-ref, and allow you to modify its members.

提交回复
热议问题