c# - Struct extension methods -
with code:
somevector.fixrounding(); //round vector's values integers if difference 1 epsilon float x = somevector.x; //still getting old value
public static void fixrounding(this vector3 v) { if (mathf.approximately(v.x, mathf.round(v.x))) v.x = mathf.round(v.x); if (mathf.approximately(v.y, mathf.round(v.y))) v.y = mathf.round(v.y); if (mathf.approximately(v.z, mathf.round(v.z))) v.z = mathf.round(v.z); }
the fixrounding method doesn't change vector's values although mathf.approximately returns true.
this declaration:
public static void fixrounding(this vector3 v)
... means v
being passed by value, , it's struct, assuming documentation correct. therefore changes make won't visible caller. need make regular method, , pass v
reference:
public static void fixrounding(ref vector3 v)
and call as:
typedeclaringmethod.fixrounding(ref pos);
here's demonstration of extension methods try modify structs passed value failing:
using system; struct vector3 { public float x, y, z; public override string tostring() => $"x={x}; y={y}; z={z}"; } static class extensions { public static void doublecomponents(this vector3 v) { v.x *= 2; v.y *= 2; v.z *= 2; } public static void doublecomponentsbyref(ref vector3 v) { v.x *= 2; v.y *= 2; v.z *= 2; } } class test { static void main() { vector3 vec = new vector3 { x = 10, y = 20, z = 30 }; console.writeline(vec); // x=10; y=20; z=30 vec.doublecomponents(); console.writeline(vec); // still x=10; y=20; z=30 extensions.doublecomponentsbyref(ref vec); console.writeline(vec); // x=20; y=40; z=60 } }
now if vector3
class, second line printed x=20; y=40; z=60... because it's struct, modifying value that's passed doesn't change caller's perspective. passing reference fixes that, hence third line of output.
Comments
Post a Comment