C#getter与只读 [英] C# getter vs readonly

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

问题描述

以下内容是否有区别?

class C
{
    // One:
    public static readonly int ValueAsAMember = 42;

    // Two:
    public static int ValueAsAProperty { get { return 42; } }
}

我习惯于以第一种方式编写常量(除非它们是私有的/内部的,在这种情况下,我将使用const关键字),但是最近我看到了第二种形式.

I'm used to writing constants the first way (unless they're private/internal, in which case I use the const keyword), but I recently saw the second form.

在可读性,约定,性能或其他方面,有没有一种方法比其他方法有优势?

Is there any advantage one way over the other in terms of readability, convention, performance, or anything else?

推荐答案

是的,有一个优点:

如果该值在将来的任何时候都可以更改(例如,在代码的未来版本中),则该值可以与时间相关,例如,它与时间相关,您可以在只读属性中支持该值,而无需更改您班级的公共界面.

If the value gets changeable at any point in the future (e.g. in a future version of your code), in a way that it is, for example, time-dependent, you can support that in the read-only property without changing the public interface of your class.

如果必须用属性替换 readonly 字段,则必须重新编译使用该类的所有其他程序集.

If you have to replace a readonly field with a property, you will have to recompile any other assemblies that use your class.

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

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