gpt4 book ai didi

c# - 为什么 C# 没有为变量和方法设计 'const'?

转载 作者:太空狗 更新时间:2023-10-29 19:47:34 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
“const correctness” in C#

我怀疑 const 已针对 C# 规范进行了简化,以简化一般语言。我们不能像使用 C++ 那样将变量引用或方法声明为 const 是否有特定原因?例如:

const MyObject o = new MyObject();  // Want const cast referenece of MyObject
o.SomeMethod(); // Theoretically legal because SomeMethod is const
o.ChangeStuff(); // Theoretically illegal because ChangeStuff is not const

class MyObject
{
public int val = 0;

public void SomeMethod() const
{
// Do stuff, but can't mutate due to const declaration.
}

public void ChangeStuff()
{
// Code mutates this instance. Can't call with const reference.
val++;
}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com