如果您有这样的不可变类型:
struct Point3
{
}
和内部的成员,如起源:
public static const Point3 Origin = new Point3 (0,0,0);
你应该使用:
new Point3 (0,0,0)
?
在我看来,既然类型不能改变,为什么会有许多本质上相同的起源?就像我们永远不会改变 0,对吧?
如何为不可变类型实现相同的目标?
如果您有这样的不可变类型:
struct Point3
{
}
和内部的成员,如起源:
public static const Point3 Origin = new Point3 (0,0,0);
你应该使用:
new Point3 (0,0,0)
?
在我看来,既然类型不能改变,为什么会有许多本质上相同的起源?就像我们永远不会改变 0,对吧?
如何为不可变类型实现相同的目标?
public static readonly Point3 Origin = new Point3(0,0,0);
正如 Andrew 所提到的,您不能使用const
它,因为它不是编译时常量。
请注意,如果您要重复使用构造函数,最好(从性能的角度)调用
new Point3()
比
new Point3(0, 0, 0)
编译器知道第一个版本只是清空内存,不需要调用任何代码。
However, I'd go along with providing an Origin
member and using that everywhere instead, where possible :)