前言

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

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. Session的默认保存路径

    在php.ini里的配置session.save_path是注释掉的,那么Seesion保存的路径在不同类型操作系统保存在什么位置? Linux:/tmp 或 /var/lib/php/session ...

  2. TypeScript 学习笔记 — 类型补充void,any, tuple ,enum,nerver, Symbol , BigInt ,unknown(三)

    目录 空值void 及(与Null 和 Undefined的区别) 任意值Any 元组类型 枚举类型 常量枚举 never 类型 1. 函数无法到达终点 2.通常校验逻辑的完整性,可以利用 never ...

  3. 解读GaussDB(for MySQL)灵活多维的二级分区表策略

    本文分享自华为云社区<GaussDB(for MySQL)创新特性:灵活多维的二级分区表策略>,作者:GaussDB 数据库. 背景介绍 分区表及二级分区表的功能,可以让数据库更加有效地管 ...

  4. Vue export & export default & import 总结

    Vue export & export default & import 总结 by:授客 QQ:1033553122 1.   实践环境 Vue 2.9.6 2.   简介 在ES6 ...

  5. ABC341

    E link 这个题目中所说的好的其实就是像\(010101\)这样一个\(0\),一个\(1\)的字符串. 那么不好的就是两个\(0\)或两个\(1\)在一起,所以判断一个区间好不好只需要判断一个区 ...

  6. LRZ

    1.在平面直角坐标系中,已知点 \(A(-2,2).B(3,4).C(0,1)\),直线 \(y=kx+b\) 过点 \(C\) 且与线段 \(AB\) 有交点,则 \(k\) 的取值范围是_____ ...

  7. NIO操作文件读写

    第一章 第一节,Buffuer 案例一  从buffur 读出数据, 创建了一个 FileInputStream 对象,并通过调用 getChannel() 方法获取了与之关联的 FileChanne ...

  8. 假期小结1学习安装VMware以及linux

    学习VMware是一项使我能够创建和管理虚拟机的技能.VMware 是一家知名的虚拟化解决方案供应商,它提供了一系列工具和软件,使我能够在一台物理计算机上创建多个独立的虚拟环境. 首先,我获取了VMw ...

  9. 【Vue】Re14 Router 第一部分(入门案例)

    一.箭头函数(Lambda匿名函数) <!DOCTYPE html> <html lang="en"> <head> <meta char ...

  10. 【Vue】Re09 Webpack 第一部分(介绍、安装、配置)

    一.Webpack的用途 webpack要解决的是统一网页资源的问题 前端工程化出现了很多问题,就是兼容性,浏览器所不能解析 所以需要一个打包,转换等方式处理 二.安装描述介绍 下载安装NodeJS, ...