我想遵循一些优秀的 C++ 建议,计算一次数组长度,然后使用一个值,而不必像这样调用函数:
而不是:
for( int i = 0; i < arr.length; ++i )
我写
const int size = arr.length; // or arr.Count()
for( int i = 0; i < size; ++i )
After read a different thread (在循环中执行 array.length 或 list.count 的成本是否昂贵) 我注意到性能增益没有实际意义,而且这是 C# 而不是 C++。
第二个原因是用一个值初始化我的数组:
const int size = arr.Length;
int[] primes_ = new int[size];
所以我的问题是这样的:
为什么我不能声明这一点?它向我吐出错误:
错误2分配给'length'的表达式必须是常量
这非常令人困惑,因为我的值是常量。但是,当我删除 const
时,poof 就会显示消息。 ...什么?
Length 的初始化读取:
来自 MSDN 的 public int Length {get;}
。这特别令人困惑,因为我的最后一个问题 (Get -Set 访问器功能因 get-set 关键字的存在而异) 明确地给了我“不可能仅声明 get 并让 set 不存在”的答案。
我不清楚为什么我可以声明 int size = arr.Length
,但不能声明 const int size = arr.Length
。为什么会这样呢?
I wanted to follow some excellent C++ advice of calculating the array length once and then using a value without having to call a function like so:
Instead of:
for( int i = 0; i < arr.length; ++i )
I write
const int size = arr.length; // or arr.Count()
for( int i = 0; i < size; ++i )
After reading a different thread (Is it costly to do array.length or list.count in a loop) I noticed that the performance gain is moot and that this is C# and not C++.
The second reason for this was to initialize my array with a value:
const int size = arr.Length;
int[] primes_ = new int[size];
So my question is this:
Why can't I declare this anyway? It spits me the error:
Error 2 The expression being assigned to 'length' must be constant
Which is very confusing because my value IS constant. However, when I remove the const
, poof goes the message. ...What?
The initialization of Length reads:
public int Length {get;}
from MSDN. Which is especially confusing because my last question (Get-Set Accessor functionality differs on existence of get-set keyword) explicitly gave me the answer of "It's not possible to declare only get and leave set absent."
It's not clear to my why I can declare int size = arr.Length
, but not const int size = arr.Length
. Why is this so?
发布评论
评论(2)
const
关键字要求在编译时知道该值 - .Net 编译器在编译代码时无法确定arr.length
的值,因此您无法将其分配给一个const
。关于您关于 getters 和 setters 的最后一个问题 - 如果您使用快捷语法,则必须声明两者仅:即
private long n { get;私人套装; }
。如果您将完整、详细的属性声明与本地字段一起使用,则可以仅声明一个 get:The
const
keyword requires the value to be known at compile time - the .Net compiler cannot determine the value ofarr.length
when you compile the code, so you can't assign it to aconst
.With regard to your last question about getters and setters - you must declare both only if you use the short cut syntax: i.e.
private long n { get; private set; }
. If you use the full, verbose property declaration with a local field, you can declare just a get:C# 中使用
const
进行定义需要一个可以在编译时求值的初始值设定项。看这里。
您可以使用
readonly
Definition with
const
in C# requires an initializer that can be evaluated at compile time.Look here.
You can use
readonly