C# const和readonly的用法(附带实例)
使用 C# 时,如果字段内容不想更改,可以使用 const 和 readonly 关键词:
【实例 1】圆面积的计算。
【实例 2】类内字段变量内容是 readonly 的应用。
设计类时,如果要设定字段为 readonly,则在属性设定时不可以有 set 设定,也可以达到只读的目的。
【实例 3】不含 set 的设定。
- const 是将字段设置为常数;
- readonly是将字段设为只读。
C# const应用在类字段中
一般会将不会改变的值在编译阶段使用 const 设为常数值。【实例 1】圆面积的计算。
Circle A = new Circle(10);
Console.WriteLine($"Area = {A.Area()}");
class Circle
{
const double pi = 3.14159;
double _r;
public Circle(double r) => _r = r;
public double Area()
{
return pi * _r * _r;
}
}
执行结果为:
Area = 314.159
C# readonly应用在类字段中
如果类的字段变量内容是只读(readonly),则在创建此字段变量内容时有下列规则:- 只能使用建构方法或是初始化方式设定其值;
- 程序执行过程其值不可更改;
- 只能有 get,不可以有 set;
【实例 2】类内字段变量内容是 readonly 的应用。
Point3D p1 = new Point3D(1, 2, 3); // OK
Console.WriteLine($"p1: x={p1._x}, y={p1._y}, z={p1._z}");
Point3D p2 = new Point3D();
p2._x = 30;
Console.WriteLine($"p2: x={p2._x}, y={p2._y}, z={p2._z}");
public class Point3D
{
public int _x;
public readonly int _y = 10; // readonly设置初始值
public readonly int _z; // readonly设置没有初始值
public Point3D() => _z = 20;
public Point3D(int x, int y, int z)
{
_x = x;
_y = y;
_z = z;
}
}
执行结果为:
p1: x=1, y=2, z=3
p2: x=30, y=10, z=20
设计类时,如果要设定字段为 readonly,则在属性设定时不可以有 set 设定,也可以达到只读的目的。
【实例 3】不含 set 的设定。
User A = new User("JK Hung", "老师");
A.PrintInfo();
class User
{
private string _name;
private string _occupation;
public User(string name, string occupation)
{
_name = name;
_occupation = occupation;
}
public string Name
{
get { return _name; }
}
public string Occupation
{
get { return _occupation; }
}
public void PrintInfo()
{
Console.WriteLine($"{Name} 是 {Occupation}");
}
}
执行结果
JK Hung 是 老师
上述程序第 13~16 行的 Name 属性和第 17~20 行的 Occupation 属性都是只有 get,没有 set,这表示 _name 和 _occupation 字段是 readonly 属性,因为无法更改它们的内容。相关文章
- C#常量(const和readonly关键字)的用法
- C#中的常量(const和readonly)
- C++ const成员变量和成员函数(常成员函数)
- C语言const int *a和int*const a 的区别详解
- C++11 constexpr和const的区别详解
- C++11 constexpr和const的区别
- C++ static_cast、dynamic_cast、const_cast和reinterpret_cast(四种类型转换运算符)
- C++类型转换(static_cast、dynamic_cast、const_cast和reinterpret_cast)
- C++强制类型转换运算符(static_cast、reinterpret_cast、const_cast和dynamic_cast)
- C++ const对象(常对象)
ICP备案:
公安联网备案: