私はC#でいくつかのシミュレーションコードに取り組んでおり、次の行に沿っていくつかのコードがあります。
public void predict(Point start, Point end)
{
end.velocity = start.velocity + dt * end.acceleration;
end.position = start.position + dt * end.velocity;
}
ここで、位置、速度、加速度は、関連する演算子で定義したいくつかのベクトルデータ型です。
私がやっているコードと同様に:
StartPoint = EndPoint;
EndPoint = CurrentPoint;
* Pointsは、いくつかのプリミティブ(double)および非プリミティブ(Vector)データ型を持つPointsのインスタンスです。
上記のコードは、以前はEndPointであったデータを指すようにStartPointを設定するだけで、EndPointはCurrentPointを指すようになるという(明らかな)問題が発生しています。
つまり、CurrentPointを再度変更すると、誤ってEndPointを変更してしまうことになります。
C ++では、Pointオブジェクト内の基になるデータのディープコピーを実行するように代入演算子を定義できるため、これを簡単に防ぐことができます。C#でこれを防ぐにはどうすればよいですか?
助けてくれてありがとう!
編集:Vectorクラスは次のように定義されます
[Serializable]
public class Vector
{
private Double[] data = new Double[Constants.Dimensions];
... snip ...
public static Vector operator +(Vector lhs, Vector rhs)
{
Vector result = new Vector();
for (UInt32 i = 0; i < Constants.dimensions; i++)
result[i] = lhs[i] + rhs[i];
return result;
}
lots more code here
}