开发者

float[] in a struct

Is it possible to have a float constant in my struct

private struct MyStruct
{
  public const fl开发者_运维知识库oat[] TEST = new float[] {1,2};
}

The preceding was my first guess but doesn't work.

Any ideas?


No. But you could do this:

private struct MyStruct
{
  public static readonly IList<float> TEST = Array.AsReadOnly(new float[] {1,2});
}

Not using Array.AsReadOnly means that people could not make TEST point to a different array, but the array you have assigned could have its contents changed.


No you cannot have a const float[]

Most commonly handled with some varient of

public static readonly float[] TEST = new float[] {1,2}; 

But that array isn't itself immutable, thus you often go along the lines of

public static readonly IList<float> TEST = new ReadOnlyCollectioN(new float[] {1,2}); 

Finally, the last option is to create your own immutable representation of a float[] that can be instantiated and provide the same actions as float[] without being modified.


Constant initializers have to be compile time constants

new float[] {1,2} 

creates a new object at runtime, not compile time. You can, however, make it a static readonly field, i.e.

public static readonly float[] TEST = new...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜