当前位置:网站首页>C - readonly and const keywords
C - readonly and const keywords
2022-07-25 23:48:00 【wumingxiaoyao】
C# - readonly and const keyword
introduction
Constants are often used in program design ,C# In language readonly, const Define constants , How to accurately define constants , What's the difference between them ?
Static and dynamic constants
Before understanding these two keywords , Let's first look at static constants and dynamic constants .
- static const :
The value is determined at compile time , Must be initialized at declaration time and cannot be changed later . - Dynamic constants :
Determine the value at run time , Can only be initialized in a declaration or constructor .
const
Use const Keyword to declare a constant field or constant local variable , It's a static constant . Constant fields and constant local variables Cannot contain variables and cannot be modified . Constants can be numbers 、 Boolean value 、 String or null quote . Don't create constants to represent information that you need to change at any time .
const matters needing attention
constandstaticCan't be used together , Because constant fields are implicitly static ,constAfter compilingstaticStatic field .
Out-of-service
newKeyword initializes a static constant , Even for a value type
const Constants cannot be variables

const Constant access
Class directly accesses const Constant .
namespace ConsoleApp1
{
class SampleClass
{
public int x;
public int y;
public const int C1 = 5;
public const int C2 = C1 + 5;
public SampleClass(int p1, int p2)
{
x = p1;
y = p2;
}
}
public class TestConst
{
public static void Main(string[] args)
{
var mC = new SampleClass(11, 22);
Console.WriteLine($"x = {
mC.x}, y = {
mC.y}");
Console.WriteLine($"C1 = {
SampleClass.C1}, C2 = {
SampleClass.C2}");
}
}
}
/* Output x = 11, y = 22 C1 = 5, C2 = 10 */
readonly
readonly Fields can only be assigned values during declaration or in the constructor of the same class . You can assign and reassign read-only fields multiple times in field declarations and constructors , Is a dynamic constant .
static readonly Static read-only fields , Read only fields are not implicitly static , So expose it at the class level , You must explicitly use static keyword .
After the constructor exits , Can't assign readonly Field . This rule has different meanings for value type and reference type :
- Because the value type directly contains data , Therefore, it belongs to readonly Fields of value type are immutable .
- Because reference types contain references to their data , Therefore, it belongs to readonly Fields of reference type must always reference the same object . The object is mutable . readonly Modifiers prevent fields from being replaced with other instances of the reference type . however , Modifiers do not prevent modifying the instance data of a field through a read-only field .

readonly Constant access
namespace ConsoleApp1
{
class SamplePoint
{
public int x;
// Initialize a readonly field
public readonly int y = 25;
public readonly int z;
public static readonly string LAGUAGE = "C#";
public SamplePoint()
{
// Initialize a readonly instance field
z = 24;
}
public SamplePoint(int p1, int p2, int p3)
{
x = p1;
y = p2;
z = p3;
}
}
public class TestConst
{
public static void Main(string[] args)
{
Console.WriteLine($"SamplePoint.LAGUAGE = {
SamplePoint.LAGUAGE}");
SamplePoint p1 = new SamplePoint(11, 21, 32); // OK
Console.WriteLine($"p1: x={
p1.x}, y={
p1.y}, z={
p1.z}");
SamplePoint p2 = new SamplePoint();
p2.x = 55; // OK
//p2.y = 66;// Error
Console.WriteLine($"p2: x={
p2.x}, y={
p2.y}, z={
p2.z}");
}
}
}
/* output SamplePoint.LAGUAGE = C# p1: x=11, y=21, z=32 p2: x=55, y=25, z=24 */
const and readonly difference
- Conceptual differences
readonlyIndicates read-only , Dynamic constants , Run time determination value ,constRepresents a static constant , The value is determined at compile time .
such as : The date of birth of a person can be defined asconstConstant , Once declared, the value will not change , And people's age age It can be defined asreadonly, You can calculate the age according to the date of birth in the constructor . - The scope of decoration is different
readonlyIt can only be modified field, Can't be decorated local variable,constModifiable field and local variable.
- Type difference
constIt can only be modified primitive type( Numbers 、 Boolean value , character ) And very special reference types string and null(string It's an immutable string , Each modification , Are equivalent to re creating a ), Why not decorate other reference types , Because other reference types cannot know their exact values at compile time . Out-of-servicenewKeyword initializes a static constant .readonlyCan be any data type , It can be usednewKeyword initializes a dynamic constant . constThe default variable isstaticClass variables , Cannot addstaticmodification ,readonlyDefault is not , It needs to be specially added static To become a class variable .- assignment
constCan only be assigned when declaring , Cannot assign values externally ,readonlyYou can assign values externally , But it can only be assigned by constructor . - efficiency
constModifier constants focus on efficiency ;readonlyModifier constants focus on flexibility .constDecorated constants have no memory consumption ;readonlyBecause you need to save constants , So there is memory consumption .
边栏推荐
- 【ManageEngine】ServiceDesk Plus荣获2022安全样板工程数据安全奖
- S4/hana mm & SD EDI Nast based integrated configuration (orders, ordrsp, desadv, invoice)
- 红娘的话
- [learning notes] unreal 4 engine introduction (IV)
- chown: changing ownership of ‘/var/lib/mysql/‘: Operation not permitted
- 三板斧!助你成为优秀软件工程师
- 获取马蜂窝酒店数据
- SAP Message No. VG202 IDoc E1EDK18 中付款条款已经转移:检查数据
- redis-基本数据类型(String/list/Set/Hash/Zset)
- C language implementation of three chess
猜你喜欢

什么是奇偶校验?如何用C语言实现?

下一代终端安全管理的关键特征与应用趋势

initializer_list工具库学习

Graph traversal DFS, BFS (code explanation)

意向不到的Dubug妙招

抽丝剥茧C语言(高阶)程序环境和预处理

Part 66: monocular 3D reconstruction point cloud

Interview focus - TCP protocol of transport layer

The process of finding free screen recording software - I didn't expect win10 to come with this function

Find the cause of program dead cycle through debugging
随机推荐
[learning notes] unreal 4 engine introduction (III)
Deep and shallow copies
Moment.js
Qpprogressbar for QT style (QSS) application
什么是奇偶校验?如何用C语言实现?
[test technology performance test LoadRunner] detailed explanation of common functions of LoadRunner
Why are there many snapshot tables in the BI system?
Part 67: conversion between keypoint and point2f in opencv
This point inside the function / change this point inside the function
Payment terms in SAP message No. vg202 IDoc e1edk18 have been transferred: check data
[intelligence question] interview intelligence question
initializer_ List tool library learning
arcgis根据矢量范围裁取tif影像(栅格数据)、批量合并shp文件、根据矢量范围裁取区域内的矢量,输出地理坐标系、转换16位TIF影像的像素深度至8位、shp文件创建和矢量框标绘设置
R language installation tutorial | graphic introduction is super detailed
LeetCode 0136. 只出现一次的数字:异或
Generating random number random learning uniform_ int_ distribution,uniform_ real_ distribution
十大排序之快速排序
【MUDUO】Thread封装
Constructors and prototypes
【MUDUO】EventLoopThreadPool