1. 概要
const 和 readonly
| 目的 | 生命周期 | 对比说明 | |
| const | 只读控制 | 定义时 | 如果不需要再设置的时候做什么特殊的处理几乎相同 |
| readonly | 构造函数式 | 更灵活一些,因为可以在构造函数的时候为其赋值。 |
2 代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Collections.Immutable;
using System.Text;
namespace ConsoleApp11
{
class Program
{
const int a = 1;
readonly int b = 1;
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
A a = new A();
a.display();
Console.ReadKey();
}
}
class A {
const int a = 1;
readonly int b = 1;
public A() {
b = 2;
}
public void display() {
Console.WriteLine($"a:{a} b:{b}");
}
}
}
3.运行结果

本文探讨了C#中const和readonly关键字的区别,包括它们的定义位置、控制范围和使用场景。const用于完全控制变量值不可变,而readonly允许在构造函数中初始化并保持不变。通过实例代码展示了两者的应用和运行结果。
744

被折叠的 条评论
为什么被折叠?



