“静态只读"与“常量" [英] 'Static readonly' vs. 'const'

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

问题描述

我已经阅读了有关 conststatic readonly 字段的内容.我们有一些只包含常量值的类.它们用于我们系统中的各种事物.所以我想知道我的观察是否正确:

I've read around about const and static readonly fields. We have some classes which contain only constant values. They are used for various things around in our system. So I am wondering if my observation is correct:

对于公开的所有内容,这些类型的常量值是否应该始终是static readonly?并且只将 const 用于内部/受保护/私有值?

Should these kind of constant values always be static readonly for everything that is public? And only use const for internal/protected/private values?

你有什么推荐?我是否应该甚至不使用 static readonly 字段,而是使用属性?

What do you recommend? Should I maybe even not use static readonly fields, but rather use properties maybe?

推荐答案

public static readonly 字段有点不寻常;public static 属性(只有一个 get)会更常见(可能由 private static readonly 字段支持).

public static readonly fields are a little unusual; public static properties (with only a get) would be more common (perhaps backed by a private static readonly field).

const 值直接烧入调用站点;这是双刃剑:

const values are burned directly into the call-site; this is double edged:

  • 如果该值是在运行时获取的,可能是从配置中获取的,那将毫无用处
  • 如果你改变了一个 const 的值,你需要重建所有的客户端
  • 但它可以更快,因为它避免了方法调用...
  • ...无论如何有时可能会被 JIT 内联

如果值永不改变,那么const就可以 - Zero 等做出合理的consts ;p 除此之外,static 属性是更常见.

If the value will never change, then const is fine - Zero etc make reasonable consts ;p Other than that, static properties are more common.

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

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