前言

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

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. Mysql中where条件自动类型转换的坑

    我有张表,其主键id字段为varchar(5),内容是5位随机不重复字符串表的内容大概是这样的 id name s8bk2 admin 9f0ps username 在一个方法中我查询了这张表,代码大 ...

  2. 基于django(爱抚宠物) 小程序设计和实现(源码+LW+部署讲解)

    感兴趣的可以先收藏起来,大家在毕设选题,项目以及论文编写等相关问题都可以给我加好友咨询 系统介绍: 科技进步的飞速发展引起人们日常生活的巨大变化,电子信息技术的飞速发展使得电子信息技术的各个领域的应用 ...

  3. [oeasy]python0096_游戏娱乐行业_雅达利_米洛华_四人赛马_影视结合游戏

    游戏娱乐行业 回忆上次内容 游戏机行业从无到有 雅达利 公司 一枝独秀 并且带领 行业 发展起来 雅达利公司 优秀员工 乔布斯 在 朋友 帮助下完成了<pong> Jobs 黑了 Woz ...

  4. oeasy教您玩转vim - 12 - # 词头词尾

    词头词尾 回忆上节课内容 我们这次学了向前一个单词 w 意思是 word 还学习了向后一个单词 b 意思是 backward 这俩命令都落在单词的第一个字母 还有什么好玩的命令吗? 动手练习 我们可以 ...

  5. 2023HACSP-J补测

    都快忘了自己还打过这个比赛了,所以来补一下. 完整题目在这里查看. Day0 来到郑州,寻找考场.幸好提前来了,因为考场大门就 5m 宽(HA用不用这么穷啊喂,来JZYZ不好么),开车转了 20min ...

  6. DASCTF 2023 & 0X401七月暑期挑战赛【PWN】(FileEditor篇)

    DASCTF 2023 & 0X401七月暑期挑战赛[PWN](FileEditor篇) 题目保护情况(保护全家桶) 64位ida逆向 模拟了一个类似vim的功能,有打开文件,打印内容,插入行 ...

  7. 搭建lnmp环境-nginx关联php-fpm (第三步)

    永久关闭防火墙sudo systemctl stop firewalldsudo systemctl disable firewall 有两个防火墙!如果上面那个关闭还不行,就继续关这个后重启.   ...

  8. linux常用命令(每日积累)

    linux查看应用程序的进程号和端口号 lsof -i :port,查看指定端口运行的程序,同时还有当前连接. netstat -nupl  (UDP类型的端口)netstat -ntpl  (TCP ...

  9. 【Spring】使用SpringTest报错 java.lang.NoSuchMethodError

    完整报错信息: "C:\Program Files\Java\jdk1.8.0_301\bin\java.exe" -ea -Didea.test.cyclic.buffer.si ...

  10. 【C3】01 概述

    CSS (层叠样式表) 让你可以创建好看的网页,但是它具体是怎么工作的呢? 这篇文章通过一些很简单的例子,告诉我们什么是 CSS, 同时还会涉及一些和 CSS 相关的专业术语. 预备知识: 基本的计算 ...