const多维数组初始化 [英] Const multi-dimensional array initialization

查看:173
本文介绍了const多维数组初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下为什么起作用?

class A
{
    public int[,] i = { { 1, 2, 3 }, { 1, 2, 3 }, { 1, 2, 3 } };

    static void Main(string[] args)
    {
    }
}

以下内容没有?

class A
{
    public const int[,] i = { { 1, 2, 3 }, { 1, 2, 3 }, { 1, 2, 3 } };

    static void Main(string[] args)
    {
    }
}

除了字符串以外,不允许为const引用类型分配null以外的任何内容.由于它是一个数组(引用),因此必须将其分配为null(?).如果它为常数且为null,将如何初始化?

It does not allow for a const reference type other than string to be assigned anything other than null. Since it's an array (reference) it must be assigned null(?). How would it be initialized if it's constant and null?

推荐答案

如果我没记错的话,它是C#语言设计的一部分. const 保留给那些可以在编译时即在程序构建之前(期间)推断出其内容的项目.C#中的所有数组都是运行时数组(它们的长度是在程序运行时确定的,而不是在此之前确定),因此无法将它们放入 const 字段中.我觉得这是C#的局限性,但这就是他们决定这样做的方式.

It's part of the language design of C#, if I remember correctly. const is reserved for items that can have their contents deduced at-compile-time, i.e. before (during) the program is even built and then run. All arrays in C# are run-time arrays (their lengths are determined when the program runs, not before then) and thus they cannot be made into const fields. I feel it's a limitation of C#, but that's how they decided to do it.

引用类型可以为null的原因是 null 是一个常量值,而您的初始化程序(在运行时创建)不是.该语言内置了 null ,因此通过这种逻辑,其值始终始终是已知的(因此可用于编译时引用类型).

The reason reference types can be null is that null is a constant value, whereas your initializer (which is made at run-time) is not. null is built into the language, so by that logic its value is always known, all the time (and thus, usable for compile-time reference types).

尽管如此,您应该能够创建一个静态表,该表将在其他任何代码使用或需要时进行初始化:

You should be able to make a static table, though, that will be initialized the moment it is used or needed by any other code:

public static int[,] i = { { 1, 2, 3 }, { 1, 2, 3 }, { 1, 2, 3 } };
       ^ Static Keyword

您可以按如下方式访问它(如果它仍在 A类中):

You can access it like (if it's still in class A):

A.i[0, 1]

希望对您有帮助

要了解更多信息,请查看MSDN:

To learn more, look at MSDN: http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&l=EN-US&k=k(CS0134);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5)&rd=true

EDIT如果您需要将静态表铆钉到代码上,并且在初始化后永远不要让任何人对其进行更改,则可以使用 readonly 关键字:

EDIT If you need to rivet the static table to the code and never let anyone change it after it's been initialized, there's the readonly keyword for that purpose:

public static readonly int[,] i = { { 1, 2, 3 }, { 1, 2, 3 }, { 1, 2, 3 } };
       ^ Static ^Readonly Keywords

请记住,它不会阻止您将内容重新分配到那些插槽中,但是它的确与C#所提供的一样固定,省去了创建属性或每次返回新数组的麻烦.

Keep in mind, it won't stop you from re-assigning things into those slots, but it's about as fixed as C# can give you, save of making a property or returning a new array every time.

这篇关于const多维数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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