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.运行结果