- 從C# 4.0開始,泛型接口和泛型委托都支持協變和逆變,由於歷史原因,數組也支持協變。
- 里氏替換原則:任何基類可以出現的地方,子類一定可以出現。
協變(out)
協變
:即自然的變化,遵循里氏替換原則,表現在代碼上則是任何基類都可以被其子類賦值,如Animal = Dog、Animal = Cat- 使用
out
關鍵字聲明(注意和方法中修飾參數的out含義不同) - 被標記的參數類型只能作為方法的返回值(包括只讀屬性)
- 在沒有協變時:
abstract class Animal {}
class Dog : Animal {}
class Cat : Animal {}
interface IPoppable<T>
{
T Pop();
}
class MyStack<T> : IPoppable<T>
{
private int _pos;
private readonly T[] _data = new T[100];
public void Push(T obj) => _data[_pos++] = obj;
public T Pop() => _data[--_pos];
}
以下代碼是無法通過編譯的
var dogs = new MyStack<Dog>();
IPoppable<Animal> animals1 = dogs; // 此處會發生編譯錯誤
Stack<Animal> animals2 = dogs; // 此處會發生編譯錯誤
此時,我們如果需要為動物園飼養員新增一個輸入參數為Stack<Animal>
飼喂的方法,一個比較好的方法是新增一個約束泛型方法:
class Zookeeper
{
public static void Feed<T>(IPoppable<T> animals) where T : Animal {}
}
// 或者
class Zookeeper
{
public static void Feed<T>(Stack<T> animals) where T : Animal {}
}
// Main
Zookeeper.Feed(dogs);
- 現在,C#增加了協變
使IPoppable<T>
接口支持協變
// 僅僅增加了一個 out 聲明
interface IPoppable<out T>
{
T Pop();
}
簡化Feed方法
class Zookeeper
{
public static void Feed(IPoppable<Animal> animals) {}
}
// Main
Zookeeper.Feed(dogs);
協變的天然特性——僅可作為方法返回值,接口(或委托)外部無法進行元素添加,確保了泛型類型安全性,所以不用擔心Dog的集合中出現Cat
- 常用的支持協變的接口和委托有:
- IEnumerable
- IEnumerator
- IQueryable
- IGrouping<out TKey, out TElement>
- Func
等共17個 - Converter<in TInput, out TOutput>
- IEnumerable
IEnumerable<Dog> dogs = Enumerable.Empty<Dog>();
IEnumerable<Animal> animals = dogs;
var dogList = new List<Dog>();
IEnumerable<Animal> animals = dogList;
- 另外,由於歷史原因,數組也支持協變,例如
var dogs = new Dog[10];
Animal[] animals = dogs;
但是無法保證類型安全性,以下代碼可正常進行編譯,但是運行時會報錯
animals[0] = new Cat(); // 運行時會報錯
逆變(in)
逆變
:即協變的逆向變化,實質上還是遵循里氏替換的原則,將子類賦值到基類上- 使用
in
關鍵字聲明 - 被標記的參數類型只能作為方法輸入參數(包括只寫屬性)
- 例如:
abstract class Animal {}
class Dog : Animal {}
class Cat : Animal {}
interface IPushable<in T>
{
void Push(T obj);
}
class MyStack<T> : IPushable<T>
{
private int _pos;
private readonly T[] _data = new T[100];
public void Push(T obj) => _data[_pos++] = obj;
public T Pop() => _data[--_pos];
}
// Main
var animals = new MyStack<Animal>();
animals.Push(new Cat());
IPushable<Dog> dogs = animals;
dogs.Push(new Dog());
逆變的天然特性——僅可作為方法輸入參數,接口(或委托)無法進行元素獲取,即只能將子類賦值到父類上,進而保證了類型安全性。
- 另外,常用支持逆變的接口和委托有:
- IComparer
- IComparable
- IEqualityComparer
- Action
等共16個 - Predicate
- Comparison
- Converter<in TInput, out TOutput>
- IComparer
Action<Animal> animalAction = new Action<Animal>(a => { });
Action<Dog> DogAction = animalAction;