1.定义
- 通常是用在类的属性上
- 使用了readonly的属性,只能在定义时或类的构造函数中初始化,除此之外不可以再修改它的值
2.作用
- 如果你希望一个数据成员在初始化后不能被改变,可以使用【readonly】关键字。
注意:这个【readonly】关键字的作用和其字面意思“只读”没有多少关系,所以尽管忽略其字面意思
3.代码
创建一个控制台项目,包含3个文件Program.cs、ReadOnlyDemo.cs、ReadOnlyDemo2.cs
Program.cs的代码:
namespace FeatureDemo
{
class Program
{
static void Main(string[] args)
{
//readonly是一个string
ReadOnlyDemo demo1 = new ReadOnlyDemo("demo1");
showResult(demo1.GetCode());
//readonly 是一个类
TestClass1 t1 = new TestClass1();
TestClass2 t2 = new TestClass2();
ReadOnlyDemo2 demo2 = new ReadOnlyDemo2(t1);
demo2.changeValue("hello");
showResult(demo2.showValue());
Console.ReadLine();
}
public static void showResult(string info)
{
Console.WriteLine(info);
}
}
}
ReadOnlyDemo.cs的代码:
using System;
using System.Collections.Generic;
using System.Text;
namespace FeatureDemo
{
public class ReadOnlyDemo
{
private readonly string _code = "empty string";
public ReadOnlyDemo(string code)
{
_code = code;
}
public string GetCode()
{
return _code;
}
//只能在初始化或构造方法中对readonly属性进行再赋值,该方法会报错
//public void ChangeCode(string newCode)
//{
// _code = newCode;
//}
}
}
ReadOnlyDemo2.cs的代码:
using Microsoft.VisualBasic.CompilerServices;
using System;
using System.Collections.Generic;
using System.Text;
namespace FeatureDemo
{
public class ReadOnlyDemo2
{
private readonly ITest _testInterface;
public ReadOnlyDemo2(ITest testInterface)
{
_testInterface = testInterface;
}
public void changeValue(String code)
{
_testInterface.setCode(code);
}
public string showValue()
{
return _testInterface.getCode();
}
//只能在初始化或构造方法中对readonly属性进行再赋值,该方法会报错
//public void changeObject(ITest testInterface)
//{
// _testInterface = testInterface;
//}
}
public class TestClass1: ITest
{
private string _code { get; set; }
public string getCode()
{
return "Test1:" + _code;
}
public void setCode(string code)
{
_code = code;
}
}
public class TestClass2: ITest
{
public string _code { get; set; }
public string getCode()
{
return "Test2:" + _code;
}
public void setCode(string code)
{
_code = code;
}
}
public interface ITest
{
public string getCode();
public void setCode(string code);
}
}
4.运行结果
5.说明
从Demo中不难发现下面几点:
- readonly定义的string一旦初始化后就不能修改其值,而如果是个类对象,是可以在初始化后修改该类中的属性值的
- 如果在readonly在定义时和构造函数中同时都对它赋值,定义时的值会被构造函数覆盖
- ReadOnlyDemo2.cs中无法实现类似changeObject这样的方法的,在依赖注入中就使用了这个特性
6.写在结尾
- 文章来源:https://blog.youkuaiyun.com/CrazyRock98
- 如果文章对你有用,不妨点个赞(如果你非要打赏那我也是可以接受的)