在C#中const的方法 [英] Const methods in C#

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

问题描述

在C ++中,你可以定义像这样一个恒定的方法:

In C++, you can define a constant method like so:

int func_that_does_not_modify_this(int arg) const {}

配售常量末的功能可以防止您从意外修改任何内部属性,并让来电者知道,这个功能不会修改对象。

Placing const at the end of the function prevents you from accidentally modifying any of the internal properties, and lets the caller know that this function won't modify the object.

有没有在C#这样的概念?

Is there a concept like this in C#?

推荐答案

没有,没有什么能像在C#。它已经谈了很多,但它是相当难以作出这样的方式const的工作,它是在编译时可核查的,不能被抛弃喜欢的话可以在C ++中,并且仍然是相当容易实际使用没有的每个人的都要得到,当他们设计自己的课程是完全正确的。

No, there's nothing like that in C#. It's been talked about a lot, but it's quite difficult to make const work in such a way that it's verifiable at compile time, can't be cast away like it can in C++, and is still reasonably easy to actually use without everyone having to get it perfectly right when they design their own classes.

当然,如果你设计自己的类型为不可变的(如字符串),然后在其上所有的实例方法都是有效的常量。这并不总是可行的,但它的使用在适当的一项重要技术。

Of course, if you design your own types to be immutable (like string) then all instance methods on it are effectively const. This isn't always practical, but it's an important technique to use where appropriate.

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

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