当前位置:网站首页>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 .
边栏推荐
- Topsis与熵权法
- 热部署和热加载有什么区别?
- [learning notes] solid works operation record
- The expression of flag=false if (flag) {return} timer=null if (timer) {return} in the throttle valve has been unclear
- sftp和ftp的区别
- Write a select drop-down list
- JS regular expression content:
- 【代码案例】博客页面设计(附完整源码)
- How does JS judge whether the current date is within a certain range
- Leetcode 0919. complete binary tree inserter: array representation of complete binary tree
猜你喜欢

Find the cause of program dead cycle through debugging

Topsis与熵权法

意向不到的Dubug妙招

Qt风格(QSS)应用之QProgressBar

Program environment and pretreatment

Release of v6.5.1/2/3 series of versions of Xingyun housekeeper: the ability of database OpenAPI continues to be strengthened

Regular expression (user name form verification / verification of landline number / regular replacement)

2022-07-18 study notes of group 5 self-cultivation class (every day)

initializer_ List tool library learning

A brief introduction to OWASP
随机推荐
R语言安装教程 | 图文介绍超详细
Leetcode 0919. complete binary tree inserter: array representation of complete binary tree
面试重点——传输层的TCP协议
[learning notes] solid works operation record
Query commodity cases (operate data with array addition method) / key points
【MUDUO】EventLoopThreadPool
S4/hana mm & SD EDI Nast based integrated configuration (orders, ordrsp, desadv, invoice)
获取马蜂窝酒店数据
Why are there many snapshot tables in the BI system?
【MUDUO】EventLoop事件循环
A brief introduction to OWASP
智牛股--09
Get the data of Mafeng Hotel
1223. 掷骰子模拟 范围DP
C# - readonly 和 const 关键字
numeric学习之iota,accumulate
[Muduo] EventLoop event cycle
1913. 两个数对之间的最大乘积差-无需排序法
typescript ts 基础知识之类
Reduce method of array