对于C++开发人员来说,它看起来很奇怪 在C++中,我们用来标记参数,const
以确保它的状态不会在方法中改变.还有其他C++特定的原因,比如const ref
为了传递ref而传递,并确保状态不会被更改.但是为什么我们不能在C#中标记为方法参数const?
为什么我不能像下面那样声明我的方法?
....
static void TestMethod1(const MyClass val)
{}
....
static void TestMethod2(const int val)
{}
....
Run Code Online (Sandbox Code Playgroud) class foo {
public readonly int bar;
};
foo a = new foo() { bar = 123 };
Run Code Online (Sandbox Code Playgroud)
error CS0191: A readonly field cannot be assigned to (except in a constructor or a variable initializer)
如何bar
在上面的对象初始化程序中指定?
我可以初始化readonly成员而无需为每个类/结构编写自定义构造函数吗?