在 C# 中声明一个 const double[]?

Declaring a const double[] in C#?(在 C# 中声明一个 const double[]?)

本文介绍了在 C# 中声明一个 const double[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个我使用的常量,我的计划是把它们放在一个双精度的 const 数组中,但是编译器不允许我这样做.

I have several constants that I use, and my plan was to put them in a const array of doubles, however the compiler won't let me.

我试过这样声明:

const double[] arr = {1, 2, 3, 4, 5, 6, 73, 8, 9 };

然后我决定将其声明为静态只读:

Then I settled on declaring it as static readonly:

static readonly double[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9};

但是问题仍然存在.为什么编译器不让我声明一个 const 值数组?或者会,我只是不知道怎么做?

However the question remains. Why won't compiler let me declare an array of const values? Or will it, and I just don't know how?

推荐答案

来自 MSDN (http://msdn.microsoft.com/en-us/library/ms228606.aspx)

常量表达式是一个表达式可以在编译时.因为只有这样创建 a 的非空值reference-type [an array] 是应用新的运算符,并且因为 new 运算符不允许在常量表达式,唯一可能的引用类型常量的值字符串以外的为空.

A constant-expression is an expression that can be fully evaluated at compile-time. Because the only way to create a non-null value of a reference-type [an array] is to apply the new operator, and because the new operator is not permitted in a constant-expression, the only possible value for constants of reference-types other than string is null.

这篇关于在 C# 中声明一个 const double[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 C# 中声明一个 const double[]?

基础教程推荐