简体   繁体   中英

How to create a const member for an immutable type?

If you have an immutable type like this:

struct Point3
{

}

and a member inside like origin:

public static const Point3 Origin = new Point3 (0,0,0);

should you use:

new Point3 (0,0,0)

?

It seems to me that since the type can not be changed, why have many origins that are essentially the same thing? Like we never change 0, right?

How to achieve the same thing for immutable types?

public static readonly Point3 Origin = new Point3(0,0,0);

As Andrew mentioned, you can't use const for this because it's not a compile-time constant.

Note that if you are going to use a constructor repeatedly, you'd be better off (from a performance point of view) calling

new Point3()

than

new Point3(0, 0, 0)

The compiler knows that the first version is just going to blank out memory, and doesn't need to call any code.

However, I'd go along with providing an Origin member and using that everywhere instead, where possible :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM