CH12.1 - CH12.2
标签(空格分隔): 泛型 generic
1. 泛型的含义
借助泛型,可以根据要处理的精确数据类型定制方法、类、结构或接口。
泛型的优点包括:代码的可重用性增加,类型安全性提高。
2. 使用泛型
2.1 可空类型nullable type
解决值类型的一个小问题 int
double
等
值类型不能为空,而引用类型可以为空
System.Nullable<T> nullableT;
nullableT
不但可以是类型T
的任意值,还可以为空。
另外可以使用HasValue
属性
2.1.1 运算符和可空类型
int? nullableInt;
nullableInt = null;//正确
2.1.2 ??运算符(空接合运算符)
op1 ?? op2
op1 == null ? op2 : op1
//三元运算
解释: 第一个不是null该运算等于第一个操作数,反之,等于第二个操作数。
2.1.3 ?.运算符(空条件运算符)
有助于避免繁杂的空值检查。
int? count = customer.orders?.Count();
//if orders is null, count = null; else count = orders.Count();
int? count = customer.orders?.Count() ?? 0;
//if orders is null, count is assigned to 0; else count = orders.Count();
触发事件
触发事件最常用方法
var onChanged = OnChanged;
if (onChanged != null)
{
onChanged(this, args);
}
这种模式不是线程安全的,改进使用空条件运算符避免异常
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>
List<Animal> animalCollection = new List<Ch12Ex02.Animal>();
animalCollection.Add(new Cow("Rual"));
animalCollection.Add(new Chicken("Dona"));
foreach(Animal myAnimal in animalCollection)
{
myAnimal.Feed();
}
2.2.2 对泛型进行排序和搜索
泛型接口IComparer<T>
和IComparable<T>
排序和搜索两个委托
Comparison:用于排序方法
Predicate:用于搜索方法
使用方法见CH12Ex03
2.2.3 Dictionary< Key,Value>
Dictionary<string, Int32> dictionary = new Dictionary<string, int>();
dictionary.Add("Green", 26);
dictionary.Add("Red", 36);
dictionary.Add("Blue", 12);
foreach(string key in dictionary.Keys)
{
Console.WriteLine(key);
}
foreach(int value in dictionary .Values)
{
Console.WriteLine(value);
}
foreach(KeyValuePair<string,int> thing in dictionary)
{
Console.WriteLine(thing.Key + " " + thing.Value);
}
键值必须唯一。
键值不唯一抛出异常ArgumenException异常。
允许把ICompare接口传递给其构造函数。
Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);
英文单词
Word | Interpretation |
---|---|
Invoke | 援引 |
Theta | θ |
radians | 弧度 |
vector | 矢量 |
Format | 格式 |
Library | 图书馆 |
victory | 胜利 |
complete | 完成 |