在 c# 中,
struct
是值类型. 但是在 dart 中, 没有东西对标struct
.
以下片断是C# 代码, 可以看到 directionVector
这个变量被初始为 Vector2.zero
, 然后又在 while 循环里对这个变量进行修改, 很正常的操作, 因为 Vector2
是 struct
, 所以 directionVector
的初始值永远都是 (0,0)
internal bool TryConvertNamedDirectionToAngle(string token, out double angle)
{
var reader = new CssReader(token, ' ');
if (reader.CanRead && reader.Read() == "to")
{
var defaultVector = Vector2.Down; // By default gradient is drawn top-down
var directionVector = Vector2.Zero;
reader.MoveNext();
while (reader.CanRead)
{
directionVector.SetNamedDirection(reader.Read());
reader.MoveNext();
}
...
...
internal struct Vector2
{
public static Vector2 Zero { get; } = new Vector2(0d, 0d);
public static Vector2 Left { get; } = new Vector2(-1d, 0d);
public static Vector2 Right { get; } = new Vector2(1d, 0d);
public static Vector2 Up { get; } = new Vector2(0d, -1d);
public static Vector2 Down { get; } = new Vector2(0d, 1d);
public double X { get; private set; }
public double Y { get; private set; }
private Vector2(double x, double y)
{
X = x;
Y = y;
}
public void SetNamedDirection(string direction)
{
switch (direction)
{
case "left":
X = -1;
break;
case "right":
X = 1;
break;
case "top":
Y = -1;
break;
case "bottom":
Y = 1;
break;
case "center":
X = 0;
Y = 0;
break;
default:
throw new ArgumentOutOfRangeException($"Unrecognized direction: '{direction}'");
}
}
...
但是 dart 中没有 struct
对标的东西, 所以只用 class 来写上面的代码:
class Vector {
///
static Vector zero = Vector(0, 0);
///
static Vector left = Vector(-1, 0);
///
static Vector right = Vector(1, 0);
///
static Vector up = Vector(0, -1);
///
static Vector down = Vector(0, 1);
///
double x;
///
double y;
///
Vector(this.x, this.y);
///
void setNamedDirection(String direction) {
switch (direction) {
case "left":
this.x = -1;
break;
case "right":
this.x = 1;
break;
case "top":
this.y = -1;
break;
case "bottom":
this.y = 1;
break;
case "center":
this.x = 0;
this.y = 0;
break;
default:
throw new Exception("Unrecognized direction: '$direction'");
}
}
这样写的问题很明显, 因为 class 是地址引用
final directionVector = Vector.zero;
对 directionVector
的任何修改, 都会直接修改 Vector.zero 的值 .
如果尝试用 const 构造函数来修改这个 Vector 类, 就会发现那根本就行不通, 因为 const 构造函数需要用 final 来修饰属性. final 的意思就是: 值不能被修改. 但是这里的场景需要对属性做更改, 所以不能使用 const .
我也尝试添加一个 copy 方法:
final directionVector = Vector.zero.copy();
...
Vector copy(){
return new Vector(this.x, this.y);
}
但是这种写法治标不治本, 保不准哪里无意就把 Vector.zero 给修改了.
貌似无解, 那只能祭出 get
了:
class Vector {
static Vector get zero => Vector(0, 0);
static Vector get left => Vector(-1, 0);
static Vector get right => Vector(1, 0);
static Vector get up => Vector(0, -1);
static Vector get down => Vector(0, 1);
...
虽然每次请求 Vector.zero 都会重新实例一个 Vector 对象, 但是解决了问题...
网友评论