开发者

How to return a reference in C#?

I'm using Vector3D structure. I encounter a situation that if I have a property like:

Vector3D MyVec {get; set;}

If I call MyVec.Normalize(); the MyVec value is not modified. I know struct is value type and the getter will shallow copy a new instance and return it, so the Normalize() method will modi开发者_运维百科fied the temp object not MyVec itself.

  1. How can I solve this situation? Vector3D is struct not class and I cannot modify this.
  2. Can I return the reference in C#?

Thanks.


Assign the created struct

MyVec = MyVec.Normalize();

As devio pointed out, if the Normalize method doesn't return a new struct (mutable struct is evil), here is your solution :

var myVec = MyVec;
myVec.Normalize();
MyVec = myVec;


A ref to a struct would result in unsafe code in .Net.

Two solutions come to mind:

  • Allow manipulation of the Vector3D struct only via the classes containing such struct properties.

  • Encapsulate Vector3D struct in a separate class and have this class pass through all struct methods as you require

    public class Vector3DProxy
    {
        Vector3D value;
    
        public Vector3D Value { get ... set ... }
    
        public void Normalize() { value.Normalize(); }
    }
    


Method can accept reference to value type.

public void Normalize(ref YourStruct pParameter)
{
//some code change pParameter
}

Normalize(ref someParameter);

Similar works and out operator: only difference, when use out pParameter can be not initialized(assigned).

Edit: But it's usable only if you have control to method, else simple assign value.


I think you only may solve this like this;

MyVec = MyVec.NormalizeVector();


public static class Extension
{
    public static Vector3D NormalizeVector(this Vector3D vec)
    {
        vec.Normalize();
        return vec;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜