9

有趣的阅读 - C#中的魔法方法

 3 years ago
source link: https://zhuanlan.zhihu.com/p/161160865
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

有趣的阅读 - C#中的魔法方法

计算机图形学话题下的优秀回答者

本文算是一篇有趣的C#语言的小技巧合集。涵盖了很多大家熟悉的C#语言的名词,但同时带来了更多大家平时忽略的细节。

例如Collection initialization,即集合初始化语法,这个从C#3以来就存在的语法,大家平时也会经常用来初始化常见的集合例如List,例如下面这样:

var list = new List<int> { 1, 2, 3};

但大家可能忽略的是,集合初始化并非是这些常见的集合的专利,只要满足以下2个条件,自定义的集合类型也可以实现这样的操作:

  • 实现IEnumerable接口
  • 声明签名为void Add(T item)的方法

例如下面这样:

public class CustomList<T>: IEnumerable
{
    public IEnumerator GetEnumerator() => throw new NotImplementedException();
    public void Add(T item) => throw new NotImplementedException();
}

当然,这只是一个小例子,更多的小技巧可以阅读原文。

需要注意的是,本文的目的并不是鼓励大家滥用这些语法技巧,而是要使它们不要太神秘。另一方面,也不应该完全避免它们。微软发明它们是为了使用,有时它们可以使你的代码更加清晰。

全文分为以下几个部分:

  • Collection initialization syntax
  • Dictionary initialization syntax
  • Deconstructors
  • Custom awaitable types
  • The query expression pattern
  • Summary

原文标题:

The Magical Methods in C#

文章链接:

欢迎阅读,希望有所帮助。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK