为什么要在C#中使用只读 [英] Why use readonly in C#

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

问题描述

可能重复:结果
什么是用C#标记一个字段作为只读好处?

Possible Duplicate:
What are the benefits to marking a field as readonly in C#?

我一直使用的只读关键字在C#中的情况下,我知道我只需要设置一个对象的引用一次(如ASP.NET页面上的一个WCF服务连接)。不是简单地确保其他对象不能超过一次设置,有什么用只读了像私人或私有静态标准参考的优势是什么?这似乎含糊。是否存在性能问题?

I've always used the readonly keyword in C# in situations where I know I'll only need to set the reference of an object once (e.g. a WCF service connection on an ASP.NET page). Other than simply ensuring objects cannot be set more than once, what are the advantages of using readonly over a standard reference like private or private static? It seems vague. Are there performance implications?

推荐答案

性能分歧放在一边,我想说的一大优势是,你在提供有用的信息什么是可变的,它是用来做什么(编辑:这是更多的价值,当别人接管维护你的代码的...)

Performance differences aside, I'd say the big advantage is that you're providing useful information on what the variable is and what it is used for (edit: This is of even more value when someone else takes over the maintenance of your code...)

此外,如你所说,它可以防止有人从覆盖你的意思是一个恒定值。我认为,单是供其使用...

Also, as you said, it prevents someone from overwriting what you meant to be a constant value. I think that alone is sufficient justification for its use...

这篇关于为什么要在C#中使用只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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