[关闭]
@sharif 2018-02-26T13:29:36.000000Z 字数 2056 阅读 880

CH12.1 - CH12.2

泛型 generic


1. 泛型的含义

2. 使用泛型

2.1 可空类型nullable type

解决值类型的一个小问题 int double
值类型不能为空,而引用类型可以为空
System.Nullable<T> nullableT;
nullableT不但可以是类型T的任意值,还可以为空。
另外可以使用HasValue属性

2.1.1 运算符和可空类型

  1. int? nullableInt;
  2. nullableInt = null;//正确

2.1.2 ??运算符(空接合运算符)

op1 ?? op2
op1 == null ? op2 : op1//三元运算
解释: 第一个不是null该运算等于第一个操作数,反之,等于第二个操作数。

2.1.3 ?.运算符(空条件运算符)

有助于避免繁杂的空值检查。

  1. int? count = customer.orders?.Count();
  2. //if orders is null, count = null; else count = orders.Count();
  3. int? count = customer.orders?.Count() ?? 0;
  4. //if orders is null, count is assigned to 0; else count = orders.Count();

触发事件
触发事件最常用方法

  1. var onChanged = OnChanged;
  2. if (onChanged != null)
  3. {
  4. onChanged(this, args);
  5. }

这种模式不是线程安全的,改进使用空条件运算符避免异常

  1. onChanged?.Invoke(this, args);

注意: 使用运算符重载方法,但是没有检查null,就会抛出 System.NullReferenceException

首先说下,invoke和begininvoke的使用有两种情况:
1. control中的invoke、begininvoke。
2. delegrate中的invoke、begininvoke。
这两种情况是不同的,我们这里要讲的是第1种。下面我们在来说下.NET中对invoke和begininvoke的官方定义。
control.invoke(参数delegate)方法:在拥有此控件的基础窗口句柄的线程上执行指定的委托。
control.begininvoke(参数delegate)方法:在创建控件的基础句柄所在线程上异步执行指定委托。
根据这两个概念我们大致理解invoke表是同步、begininvoke表示异步。

2.2 System.Collections.Generic

此名称空间包含用于处理集合类的泛型类型。
表 泛型集合类型

类型 说明
List<T> T类型对象的集合
Dictionary<K,V> 与k类型的键值相关的V类型

2.2.1 List< T>

  1. List<Animal> animalCollection = new List<Ch12Ex02.Animal>();
  2. animalCollection.Add(new Cow("Rual"));
  3. animalCollection.Add(new Chicken("Dona"));
  4. foreach(Animal myAnimal in animalCollection)
  5. {
  6. myAnimal.Feed();
  7. }

2.2.2 对泛型进行排序和搜索

泛型接口IComparer<T>IComparable<T>
排序和搜索两个委托
Comparison:用于排序方法
Predicate:用于搜索方法
使用方法见CH12Ex03

2.2.3 Dictionary< Key,Value>

  1. Dictionary<string, Int32> dictionary = new Dictionary<string, int>();
  2. dictionary.Add("Green", 26);
  3. dictionary.Add("Red", 36);
  4. dictionary.Add("Blue", 12);
  5. foreach(string key in dictionary.Keys)
  6. {
  7. Console.WriteLine(key);
  8. }
  9. foreach(int value in dictionary .Values)
  10. {
  11. Console.WriteLine(value);
  12. }
  13. foreach(KeyValuePair<string,int> thing in dictionary)
  14. {
  15. Console.WriteLine(thing.Key + " " + thing.Value);
  16. }

键值必须唯一。
键值不唯一抛出异常ArgumenException异常。
允许把ICompare接口传递给其构造函数。
Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);

英文单词

Word Interpretation
Invoke 援引
Theta θ
radians 弧度
vector 矢量
Format 格式
Library 图书馆
victory 胜利
complete 完成
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注