C#中的const形参

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#中的const形参相关的知识,希望对你有一定的参考价值。

C#中没有C++中的const形参,那C#中如何达到和它一样的效果?即参数不允许修改。我本来想ref一个const参数,这样该参数就不会被修改了,可是C#不允许ref const参数,ref的只能是可赋值的变量。
请高手不吝赐教,非常感激。
1L:你好,但是你再函数里面可以对这个形参进行修改,而C++的const形参你是不能修改的。也是就是我只能让你在函数中用这个值,而不能让你改这个值。
2L的,你好,readonly只能用来修饰类字段。
3L,你好,这个我之前也试过的,但是一样可以修改,根本不报错。。。不信你可以试下。

参考技术A 汗,你不用关键字ref直接传递一个值类型变量进去 就只是这个值类型的副本,在方法体中就算改变了那个值类型副本 又不影响你实际的那个值类型变量啊

你到底想干啥子哦本回答被提问者采纳
参考技术B 其实不用ref const,比如string, 你就直接ref string就可以了,而定义这个string的时候,前面加上const就ok了。我想这就是楼主想要的效果吧。 参考技术C 只有C++才会有这个疑问,我也是
int Add(const int& aa)

保护aa永远不会被动到,而只利用其计算别的东西,很多函数组合就不会出错。确保参数传入传出是一致的,c#好像不行
参考技术D There is no equivalent for C# and it has been asked many, many, many, many times before.
If you don't want anyone to alter the "reference", or perhaps you mean the content of the object, make sure the class doesn't expose any public setters or methods of mutating the class. If you cannot change the class, have it implement an interface that only publicly exposes the members in a read-only fashion and pass the interface reference instead.
If you mean you want to stop the method from changing the reference, then by default if you pass it "by reference", you are actually passing the reference by value. Any attempt from the method to change what the reference points to will only affect the local method copy, not the caller's copy. This can be changed by using the ref keyword on a reference type, at which point the method can point the reference at a new underlying object and it will affect the caller.
第5个回答  2010-05-13 C#中const是声明常量的关键字!

以上是关于C#中的const形参的主要内容,如果未能解决你的问题,请参考以下文章

C#中的staticreadonly与const的比较

关于函数形参

const形参与非const形参

重载和const形参

重载和const形参

C# 7.2 const vs referenced(in) 函数参数传递中的只读字段