声明一个长常量字节数组 [英] Declaring a long constant byte array

查看:95
本文介绍了声明一个长常量字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长字节数组,需要在C#代码中声明。我做这样的事情:

I have a long byte array that I need to declare in my C# code. I do something like this:

public static class Definitions
{
    public const byte[] gLongByteArray = new byte[] { 
        1, 2, 3,
        //and so on
    };
}

但是我收到一个错误,指出const数组只能用null初始化。

But I get an error that the const array may be initialized only with nulls.

如果我将 const 更改为 static ,它将编译,但是我的问题是-当我将其声明为 public static byte [] gLongByteArray 时,它不会在每次应用加载时都初始化,对吗?在这种情况下, gLongByteArray 变量将仅指向加载到内存中的已编译exe / dll文件中定义的数组。我问的原因是因为这个数组很长,我不希望我的程序每次启动应用程序时都浪费CPU周期来加载它,或更糟糕的是,该类被引用了...

If I change const to static it compiles, but the question I have is this -- when I declare it as public static byte[] gLongByteArray it won't be initialized every time my app loads, right? In that case the gLongByteArray variable will simply point to an array that is defined in the compiled exe/dll file that loads into memory. The reason I'm asking is because this array is pretty long and I don't want my program to waste CPU cycles on loading it every time the app starts, or worse, this class is referenced...

推荐答案

编译时常量(使用 const 关键字声明的常量) )受到严格限制。无需执行任何代码即可获取这样的常数,否则,它不能是编译时常数。 const 常量默认为静态

Compile-time constants (those declared with the const keyword) are severely restricted. No code must be executed to get such a constant, or otherwise it could not be a compile-time constant. const constants are static by default.

如果想要创建一个常量并且不能使用编译时常量,可以使用 static只读代替:

If you want to create a constant and you cannot use a compile-time constant, you can use static readonly instead:

public static readonly byte[] longByteArray = new byte[] { 1, 2, 3, 4, 5 };

static 关键字可确保仅对其进行初始化一次,并且是声明类型的一部分(而不是每个实例)。 只读关键字可确保 longByteArray 变量之后不能更改。

The static keyword ensures it is initialized only once, and part of the declaring type (and not each instance). The readonly keyword ensures the longByteArray variable cannot be changed afterwards.

Definitions.longByteArray = new byte[] { 4, 5, 6 };   // Not possible.

警告:数组是可变的,因此在上面的代码中我可以仍然这样做:

Warning: An array is mutable, so in the above code I can still do this:

Definitions.longByteArray[3] = 82;                    // Allowed.

为防止这种情况,请将类型设置为不是数组,而是一个只读的收集接口,例如< a href = http://msdn.microsoft.com/zh-cn/library/9eekhta0.aspx rel = noreferrer> IEnumerable< T> IReadOnlyList< T> ,甚至更好的是只读集合类型,例如 ReadOnlyCollection< T> 甚至不允许通过强制转换进行修改。

To prevent that, make the type not an array but a read-only collection interface, such as IEnumerable<T> or IReadOnlyList<T>, or even better a read-only collection type such as ReadOnlyCollection<T> which doesn't even allow modification through casting.

public static readonly IReadOnlyList<byte> longByteArray = new byte[] { 1, 2, 3, 4, 5 };

这篇关于声明一个长常量字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆