前言

心血来潮,这篇讲点基础的东西。

Field

比起 Property,Field 很不起眼,你若问 JavaScript,它甚至都没有 Field。

但在 C#,class 里头真正装 value 的其实是 Field,Property 只是 Filed 的读写器而已。

Field 长这样

public class Person
{
public int Age;
}

使用

var person = new Person();
Console.WriteLine(person.Age); // int default is 0
person.Age = 10; // set value
Console.WriteLine(person.Age); // get value: 10

const, readonly and init value

如果一个 Field 只能读,不能写,那我们可以用 const 去声明它。

public class Person
{
public const int Age = 5;
public const int Age2; // Error: A const field requires a value to be provided
} var person = new Person();
person.Age = 10; // Error : A readonly field cannot be assigned

const 的 init value 是写在 Filed 的结尾,一定要写 init value 哦,不然会报错。

readonly 也是用来声明只读 Field,它和 const 的不同在于,它比较宽松,在 constructor 阶段也允许 set init value。

public class Person
{
public readonly int Age = 1;
public readonly int Age2; // no error
public Person()
{
Age2 = 2; // if here no set init value Age2 will error.
}
}

如果两个都 set,construtor 会 override 掉 field assign。

注:下面这个写法是不 ok 的,它已经不算是 constructor 阶段的 set init value 了。

var person = new Person
{
Age = 15 // Error: A readonly field cannot be assigned
};

Field 的日常(Dependancy Injection)

平时很少会使用 Field 的,绝大部分情况我们用 Property,除了 Dependancy Injection。

public class HomeModel : PageModel
{
private readonly ILogger _logger; public HomeModel(ILogger<HomeModel> logger)
{
_logger = logger;
} public void OnGet()
{
_logger.LogInformation("Hello World");
}
}

一个 readonly Field,通过 construtor set init value,然后使用。

C# 12.0 primary construtor 的写法

public class HomeModel(ILogger<HomeModel> logger) : PageModel
{
public void OnGet()
{
logger.LogInformation("Hello World");
}
}

primary construtor 的 parameter 会被 compile 成 private Field,所以上面的代码和上一 part 的代码基本上是一样的。

唯一的不同是 primary construtor 目前无法声明 readonly Field。所以如果我们要 readonly 那就得多加一行。

public class HomeModel(ILogger<HomeModel> logger) : PageModel
{
private readonly ILogger _logger = logger;
public void OnGet()
{
_logger.LogInformation("Hello World");
logger.LogInformation("Hello World"); // 注意:logger 依然是可用的,因为它就是一个 Field 啊
}
}

Property

Property 是 Filed 的读写器,它长这样。

public class Person()
{
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
}

Filed 负责保存 value,Property 负责拦截读写过程。

这个是完整的写法,但日常生活中,大部分情况我们会用语法糖。

Auto Property

public class Person()
{
public int Age { get; set; }
}

Auto Property 是一种语法糖写法,前面是 Field,后面配上一个 { get; set; } 表达。它 compile 后长这样。

compiler 会替我们拆开它们。最终任然是一个 Field、一个 get 方法、一个 set 方法。

readonly = no set

public class Person()
{
public int Age { get; }
}

把 set 去掉就相等于 readonly Filed。注:没有 readonly Property 的,只有 no set。

set init value 的规则和 Field 一样。

public class Person
{
public int Age { get; } = 1;
public Person()
{
Age = 2;
}
} var person = new Person
{
Age = 3 // Error: Property or indexer 'Person.Age' cannot be assigned to -- it is read only
}

init keyword

上面例子中,实例化 Person 时,赋值是会报错的。这个是 readonly Field 的规则,我们只可以通过 construtor parameter 去实现 init 赋值。

这样局限太大了,于是 C# 6.0 推出了 init keyword。

public int Age { get; init; } = 1;

var person = new Person
{
Age = 3 // no more error
};

把 set 换成 init,它相等于 readonly 但是又允许实例化时赋值。

小总结:

有 3 个层次 assign value:field assign -> constructor assign -> new assign

它们分别对应 keyword:const -> readonly / no set -> init

required keyword

public class Person
{
public string Name { get; } // Warning Non-nullable property 'Name' must contain a non-null value
}

这是一个 readonly Property,它有一个 warning,因为我没有声明 init value。

public class Person
{
public string Name { get; } = "init value";
public Person()
{
Name = "init value";
}
}

我可以通过 2 种方式去设置 init value。这样就不会有 warning 了。

但是...如果它是 init keyword 呢?

public class Person
{
public string Name { get; init; } // Warning: Non-nullable property 'Name' must contain a non-null value
}

init 允许我们在实例化时才给予 init value,也就是说 class 内是可以不需要声明 init value 的。

但这导致它又 Warning 了。为了解决这个问题,C# 11 推出了 required keyword。

public class Person
{
public required string Name { get; init; }
}

声明 required keyword 后,它就不会 Warning 了。与此同时

var person = new Person(); // Error: Required member 'Person.Name' must be set

如果在实例化时忘记给予 init value,它还会报错提醒我们哦。

泛型限制也会报错哦

public class PersonOptions
{
public required string Name { get; set; }
} public class Person<T> where T : new() // 泛型限制 T 必须允许无参数实例化
{
} var person = new Person<PersonOptions>(); // Error : 'PersonOptions' cannot satisfy the 'new()' constraint

Best Practice

不限制模式

public class Person
{
public string Name { get; set; } = "";
public List<string> Values { get; set; } = [];
public Person Child { get; set; } = null!;
}

这个是最常见的定义,不做限制的好处是定义的时候省脑力,但对使用者来说就需要自己顾好好。

限制模式

public record class Person
{
public required string Name { get; init; }
public required List<string> Values { get; init; }
public required Person Child { get; init; }
}

record + required + init 可以很大的限制对象的读写。

对使用者来说是好事,不会忘记赋值,也不会不小心修改到值。

总结

这篇介绍了 class, filed, property, const, readonly, get, set, init, required 的基本使用方式。

它之所以有点混乱,主要是因为 C# 是经过了许多版本才一点一点逐步推出这些特性的。

这些特性和 private, protected, public 类似,都是用于限制 class 的使用者,如果使用者乖乖的话,其实我们大可不必去写这些限制。

C# – class, filed, property, const, readonly, get, set, init, required 使用基础的更多相关文章

  1. Swift - Property ''not initialized at super.init call

    Property ''not initialized at super.init call 这个错误应该挺常见的的,为什么在百度上没有找到呢,stack over flow找到了,也不能说是什么解决办 ...

  2. org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'null' to required type 'double' for property 'band'; nested exception is org.springframework.core.convert.Con

    本文为博主原创,未经允许不得转载: 先将异常粘贴出来: 20:37:26,909 ERROR [com.suning.fucdn.controller.ProductDataStaticsContro ...

  3. C# const, readonly, static readonly

    转: Const 定义的是静态常在对象初始化的时候赋值.以后不能改变它的值.属于编译时常量.不能用new初始化. Readonly 是只读变量.属于运行时变量.可以在类constructor里改变它的 ...

  4. const,readonly 这些你真的懂吗? 也许会被面试到哦。。。

    首先不可否认,这些在面试上会经常被面试官问起,但是你回答的让面试官满意吗?当然如果你知道了这些原理,或许你就不 怕了.既然说到了原理,我们还是从MSDN说起. 一:值得推敲的几个地方 1.先来看看ms ...

  5. static const readonly

    C#中的static 和Java中的static 简单,两者用法完全是一致的.从两方面讨论: 1. 变量是属于类的,不是实例级别的.只能通过类名调用,不能通过实例调用. 2. 如果在定义时就赋值了,那 ...

  6. 如何使用C#关键字const,readonly,static

    如果有一个值不太会变化,我们经常使用const和readonly,这2者有何不同呢?有时候,我们也会在readonly之前加上关键字static,这又意味着什么呢? const ● const默认是静 ...

  7. 二道Const,readonly 和 override, new的面试题

    1. Const 和 readonly ; ; ; ; static void Main(string[] args) { Console.WriteLine("aa:{0},bb:{1}, ...

  8. Java的Final和C#的Const,Readonly比较分析(转载)

    Java里面没有readonly关键字,预留了const的关键字,目前还没有实际用途,在Java中,跟这两个关键字比较接近的是final; C#中,两者都存在并可用.两者修饰的全局变量或局部变量都不能 ...

  9. C#面向对象几组关键字的详解(this,base,dynamic,var,const,readonly,is,as)

    × 目录 [1]this和base的区别 [2]var和dynamic的区别 [3]const和readonly的区别 [4]is和as的区别 这几个关键字,在用法上有许多相似之处.这里主要看看细节之 ...

  10. const readonly

    静态常量(compile-time constants)静态常量是指编译器在编译时候会对常量进行解析,并将常量的值替换成初始化的那个值. 动态常量(runtime constants)而动态常量的值则 ...

随机推荐

  1. Linux 文件夹和文件操作【Linux 常用命令系列一】

    〇.前言 本文首先介绍了 Linux 中文件的结构,将全部文件夹罗列并介绍了大概的用途: 然后通过实例介绍了文件夹相关的常用操作,仅供参考. 一.Linux 系统的文件结构 列一下系统全部文件夹: / ...

  2. [oeasy]python0117 文字的演化_埃及圣书体_象形文字_楔形文字

    埃及圣书体 回忆上次内容 两河流域 苏美尔文明 所使用的 楔形文字 不是象形文字     ​   添加图片注释,不超过 140 字(可选)   楔形文字的字型 究竟是怎么来的呢?   巴别塔 苏美尔的 ...

  3. JavaScript中的new map()和new set()使用详细(new map()和new set()的区别)

    简介:new Map(): 在JavaScript中,new Map()用于创建一个新的 Map 对象.Map 对象是一种键值对的集合,其中的键是唯一的,值可以重复.new Set(): 在JavaS ...

  4. 搭建lnmp环境-redis(第四步)

    1.下载epel仓库 (前面安装过了) yum install epel-release -y 2.下载redis数据库 yum install redis -y 3.启动redis服务 system ...

  5. 微服务:nacos服务注册与发现

    服务治理的三个角色: 服务提供者:订阅服务 服务消费者:注册服务 注册中心:记录与监控服务状态,推送服务变更信息.提供者定时发送心跳检测,心跳检测失败,就会向消费者推送变更 提供者通过负载均衡的算法选 ...

  6. SpringTask

    SpringTask是spring提供的一个任务调度工具,按照约定的时间自动执行代码逻辑 定时任务框架,即定时自动执行某段代码 应用场景:信用卡每月还款提醒,火车售票系统处理未支付订单 cron表达式 ...

  7. 安全可信,Solon v2.8.6 发布

    Solon 框架! Java "纯血国产"应用开发框架.开放原子开源基金会,孵化项目.从零开始构建(非 java-ee 架构),有灵活的接口规范与开放生态. 追求: 更快.更小.更 ...

  8. 备份服务器eBackup

    目录 软件包方式安装eBackup备份软件   1.前景提要   2.创建虚拟机   3.安装备份软件.   4.安装 eBackup 补丁   5.配置 eBackup 服务器   6.访问web界 ...

  9. Net8将Serilog日志推送ES,附视频

    这是一个Serilog的实践Demo,包括了区别记录存放,AOP 日志记录,EF 执行记录,并且将日志推送到Elastic Search. 说在前面的话 自从AI出来之后,学习的曲线瞬间变缓了,学习的 ...

  10. 【Spring-Security】Re13 Oauth2协议P3 整合JWT

    视频地址: https://www.bilibili.com/video/BV12D4y1U7D8?p=44 有用到Redis存储JWT,头疼每次找Windows版的 https://github.c ...