开发者

How can I create a public const Size in C#?

I am trying to write the following code:

public const Size ImageSize = new Size() { Width = 28, Height = 28 };

But I get the error that Width and Height are read-only.

What is the recommended way to do th开发者_JAVA百科is?


const is restricted to primitives that the compiler can directly write as IL directly. readonly should suffice here if Size is treated as immutable, i.e.

public static readonly Size ImageSize = new Size(28,28);

Note that if Size is a mutable struct, bad things can happen; I would recommend a property rather than a field to prevent a number of confusing side-effects.


The fundamental problem is that you cannot declare an object of type System.Drawing.Size as const. That indicates that the symbol is to be replaced at compile-time with the value of the constant.

Instead, you should use readonly. This is also a "constant" value in the sense that it cannot be modified once the constructor has run, but the objects are created at run-time instead of compile-time.

The following code compiles just fine:

public static readonly Size ImageSize = new Size() { Width = 28, Height = 28 };


public static readonly Size ImageSize = new Size(28,28);


You have to do this instead:

public readonly Size ImageSize = new Size(28, 28);

Making the instance read only to prevent it to be changed, as you cannot create Size as a constant.

From the docs:

A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and null.


The code you're writing:

public const Size ImageSize = new Size() { Width = 28, Height = 28 };

Actually compiles down to the same as this:

public const Size ImageSize = new Size();
ImageSize.Width = 28;
ImageSize.Height = 28;

The version your using, called the object initializer, is just syntactic shorthand for the latter version above. The two are logically identical. In the latter version you can see why it's giving you the error, you can't set properties on a const after it's been declared.

More to the point, I'm not sure if you can even use a reference type like that as a const. I'm not sure about that, as I can't say I ever tried it. You may try readonly instead. Though you may run into the same or similar issue.

Does Size have a constructor you can call with the parameters, rather than using the object initializer?


You can use :

public static readonly Size ImageSize = new Size(28, 28);

It's not actually a const, but it won't be changed after the initialization.


You need to use a constructor that takes width and height as parameters. Also, the expression must be completely evaluable during compile time. That might not work with your Size type (don't know which one it is). If so (like with System.Drawing.Size), you might consider using readonly instead of const.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜