C#中的const函数参数 [英] Const function parameter in C#

查看:81
本文介绍了C#中的const函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
的只读(类似于const的)函数参数C#
为什么没有const成员C#和const参数中的方法?

我曾经用C ++编程过,我记得我们可以在一个方法中做一个恒定的引用/指针参数.

Having programmed in C++ in the past, I recall we could make a constant reference/pointer parameter in a method.

如果我的记忆正确,则表示该方法无法更改引用,并且引用本身是常量引用.

If my memory is correct, the below means, that the method cannot alter the reference and the reference itself is a constant reference.

void DisplayData(const string &value) const
{
   std::count << value << endl;
}

C#中的类中的方法是否等效?

Is there an equivalent in C# for methods in a class?

我要问的原因是,我试图通过引用传递对象(为了提高速度),同时又不想让任何人更改它.

The reason why I'm asking is, I'm trying to pass a object by reference (for speed) and at the same time don't want anyone to alter it.

推荐答案

更新16/09/2020

现在似乎是 in 参数修饰符表现出这种行为(本质上是 ref只读).简要搜索何时使用此功能会产生以下答案:

There now appears to be the in parameter modifier that exhibits this behaviour (in essence, a ref readonly). A brief search on when you would ever use this yields the following answer:

为什么一个人会使用"; in"C#中的参数修饰符?

原始答案

没有C#等效项,并且已被问到很多很多

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.

如果您要停止该方法更改引用,那么默认情况下,如果您按引用"传递该方法,则实际上是按值传递该引用.从方法更改引用所指向的内容的任何尝试只会影响本地方法副本,而不会影响调用者的副本.可以通过在引用类型上使用 ref 关键字来更改此值,此时,方法 可以将引用指向新的基础对象,并且影响呼叫者.

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.

这篇关于C#中的const函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆