C# - 逆變的具體應用場景
前言
早期在學習泛型的協變與逆變時,網上的文章講解、例子算是能看懂,但關於 逆變的具體應用場景 這方面的知識,我並沒有深刻的認識。
本文將在具體的場景下,從泛型接口設計的角度出發,逐步探討逆變的作用,以及它能幫助我們解決哪方面的問題?
這篇文章算是協變、逆變知識的感悟和分享,開始之前,你應該先了解 協變、逆變的基本概念 ,這類文章很多,這裏就不再贅述。
協變的應用場景
雖然協變不是今天的主要內容,但在此之前,我還是想提一下關於協變的應用場景。
其中最常見的應用場景就是——如果方法的某個參數是一個 集合
時,我習慣將這個 集合
參數定義為 IEnumerable<T>
類型。
class Program { public static void Save(IEnumerable<Animal> animals) { // TODO } } public class Animal { }
IEnumerable<T>
中的 T
就是標記了代表協變的關鍵字 out
namespace System.Collections.Generic { public interface IEnumerable<out T> : IEnumerable { IEnumerator<T> GetEnumerator(); } }
假如泛型 T
為父類 Animal
類型, Dog
為 Animal
的子類,其他人在調用這個方法時,
不僅可以傳入 IEnumerable<Animal>
、 List<Animal>
、 Animal[]
類型的參數,
還可以傳入 IEnumerable<Dog>
、 List<Dog>
、 Dog[]
等其他繼承自 IEnumerable<Animal>
類型的參數。
這樣,方法的兼容性會更強。
class Program { public static void Save(IEnumerable<Animal> animals) { // TODO } static void Main(string[] args) { var animalList = new List<Animal>(); var animalArray = new Animal[] { }; var dogList = new List<Dog>(); var dogArray = new Dog[] { }; Save(animalList); Save(animalArray); Save(dogList); Save(dogArray); } } public class Animal { } public class Dog : Animal { }
逆變的應用場景
提起逆變,可能大家見過類似下面這段代碼:
class Program { static void Main(string[] args) { IComparer<Animal> animalComparer = new AnimalComparer(); IComparer<Dog> dogComparer = animalComparer;// 將 IComparer<Animal> 賦值給 IComparer<Dog> } } public class AnimalComparer : IComparer<Animal> { // 省略具體實現 }
IComparer<T>
中的 T
就是標記了代表逆變的關鍵字 in
namespace System.Collections.Generic { public interface IComparer<in T> { int Compare(T? x, T? y); } }
在看完這段代碼後,不知道你們是否跟我有一樣的想法:道理都懂,可是具體的應用場景呢?
要探索逆變可以幫助我們解決哪些問題,我們試着從另一個角度出發——在某個場景下,不使用逆變,是否會遇到某些問題。
假設我們需要保存各種基礎資料,根據需求我們定義了對應的接口,以及完成了對應接口的實現。這裏假設 Animal
與 Human
就是其中的兩種基礎資料類型。
public interface IAnimalService { void Save(Animal entity); } public interface IHumanService { void Save(Human entity); } public class AnimalService : IAnimalService { public void Save(Animal entity) { // TODO } } public class HumanService : IHumanService { public void Save(Human entity) { // TODO } } public class Animal { } public class Human { }
現在增加一個批量保存基礎資料的功能,並且實時返回保存進度。
public class BatchSaveService { private static readonly IAnimalService _animalSvc; private static readonly IHumanService _humanSvc; // 省略依賴注入代碼 public void BatchSaveAnimal(IEnumerable<Animal> entities) { foreach (var animal in entities) { _animalSvc.Save(animal); // 省略監聽進度代碼 } } public void BatchSaveHuman(IEnumerable<Human> entities) { foreach (var human in entities) { _humanSvc.Save(human); // 省略監聽進度代碼 } } }
完成上面代碼後,我們可以發現,監聽進度的代碼寫了兩次,如果像這樣的基礎資料類型很多,想要修改監聽進度的代碼,則會牽一髮而動全身,這樣的代碼就不便於維護。
為了使代碼能夠複用,我們需要抽象出一個保存基礎資料的接口 ISave<T>
。
使 IAnimalService
、 IHumanService
繼承 ISave<T>
,將泛型 T
分別定義為 Animal
、 Human
public interface ISave<T> { void Save(T entity); } public interface IAnimalService : ISave<Animal> { } public interface IHumanService : ISave<Human> { }
這樣,就可以將 BatchSaveAnimal()
和 BatchSaveHuman()
合併為一個 BatchSave<T>()
public class BatchSaveService { private static readonly IServiceProvider _svcProvider; // 省略依賴注入代碼 public void BatchSave<T>(IEnumerable<T> animals) { ISave<T> service = _svcProvider.GetRequiredService<ISave<T>>();// GetRequiredService()會在無對應接口實現時拋出錯誤 foreach (T animal in animals) { service.Save(animal); // 省略監聽進度代碼 } } }
重構後的代碼達到了可複用、易維護的目的,但很快你會發現新的問題。
在調用重構後的 BatchSave<T>()
時,傳入 Human
類型的集合參數,或 Animal
類型的集合參數,代碼能夠正常運行,
但在傳入 Dog
類型的集合參數時,代碼在運行到第8行時會報錯,因為我們並沒有實現 ISave<Dog>
接口。
雖然 Dog
是 Animal
的子類,但卻不能使用保存 Animal
的方法,這肯定會被接口調用者吐槽,因為它不符合 里氏替換原則
。
static void Main(string[] args) { List<Human> humans = new() { new Human() }; List<Animal> animals = new() { new Animal() }; List<Dog> dogs = new() { new Dog() }; var saveSvc = new BatchSaveService(); saveSvc.BatchSave(humans); saveSvc.BatchSave(animals); saveSvc.BatchSave(dogs);// 由於沒有實現ISave<Dog>接口,因此代碼運行時會報錯 }
在 T
為 Dog
時,要想獲取 ISave<Animal>
這個不相關的服務,我們可以從 IServiceCollection
服務集合中去找。
雖然我們拿到了註冊的所有服務,但如何才能在 T
為 Dog
類型時,拿到對應 ISave<Animal>
服務呢?
這時,逆變就派上用場了,
我們將接口 ISave<T>
加上關鍵字 in
後,就可以將 ISave<Animal>
分配給 ISave<Dog>
public class BatchSaveService { private static readonly IServiceProvider _svcProvider; private static readonly IServiceCollection _svcCollection; // 省略依賴注入代碼 public void BatchSave<T>(IEnumerable<T> entities) { // 假設T為Dog,只有在ISave<T>接口標記為逆變時, // typeof(ISave<Animal>).IsAssignableTo(typeof(ISave<Dog>)),才會是true Type serviceType = _svcCollection.Single(x => x.ServiceType.IsAssignableTo(typeof(ISave<T>))).ServiceType; ISave<T> service = _svcProvider.GetRequiredService(serviceType) as ISave<T>;// ISave<Animal> as ISave<Dog> foreach (T entity in entities) { service.Save(entity); // 省略監聽進度代碼 } } }
現在 BatchSave<T>()
算是符合里氏替換原則,但這樣的寫法也有缺點
-
優點:調用時,寫法乾淨簡潔,不需要設置過多的泛型參數,只需要將傳入對應的參數變量即可。
-
缺點:如果傳入的參數沒有對應的接口實現,編譯仍然會通過,只有在代碼運行時才會報錯,提示不夠積極、友好。
並且如果我們實現了
ISave<Dog>
接口,那代碼運行到第11行時會得到ISave<Dog>
和ISave<Animal>
兩個結果,不具有唯一性。
要想在錯誤使用接口時,編譯器及時提示錯誤,可以將接口重構成下面這樣
public class BatchSaveService { private static readonly IServiceProvider _svcProvider; // 省略依賴注入代碼 public void BatchSave<TService, T>(IEnumerable<T> entities) where TService : ISave<T> { ISave<T> service = _svcProvider.GetService<TService>(); foreach (T entity in entities) { service.Save(entity); // 省略監聽進度代碼 } } } class Program { static void Main(string[] args) { List<Human> humans = new() { new Human() }; List<Animal> animals = new() { new Animal() }; List<Dog> dogs = new() { new Dog() }; var saveSvc = new BatchSaveService(); saveSvc.BatchSave<IHumanService, Human>(humans); saveSvc.BatchSave<IAnimalService, Animal>(animals); saveSvc.BatchSave<IAnimalService, Dog>(dogs); // 假如實現了繼承ISave<Dog>的接口IDogService,可以改為 // saveSvc.BatchSave<IDogService, Dog>(dogs); } }
這樣在錯誤使用接口時,編譯器就會及時報錯,但由於需要設置多個泛型參數,使用起來會有些麻煩。
討論
以上是我遇見的比較常見的關於逆變的應用場景,上述兩種方式你覺得哪種更好?是否有更好的設計方式?或者大家在寫代碼時遇見過哪些逆變的應用場景?
歡迎大家留言討論和分享。
- 【Java面試】RDB 和 AOF 的實現原理、優缺點
- HMS Core音頻編輯服務3D音頻技術,助力打造沉浸式聽覺盛宴
- Spring框架系列(9) - Spring AOP實現原理詳解之AOP切面的實現
- 【算法篇】刷了兩道大廠面試題,含淚 ”重學數組“
- 2022 開源軟件安全狀況報吿:超 41% 的企業對開源安全沒有足夠的信心
- JavaScript中async和await的使用以及隊列問題
- Flex & Bison 開始
- Obsidian基礎教程
- 分享自己平時使用的socket多客户端通信的代碼技術點和軟件使用
- iNeuOS工業互聯網操作系統,增加2154個視圖建模(WEB組態)行業矢量圖元、大屏背景及相關圖元
- 多台雲服務器的 Kubernetes 集羣搭建
- Elasticsearch學習系列四(聚合搜索)
- 關於swiper插件在vue2的使用
- 使用 Abp.Zero 搭建第三方登錄模塊(一):原理篇
- LVGL庫入門教程 - 顏色和圖像
- Node.js精進(4)——事件觸發器
- 物聯網?快來看 Arduino 上雲啦
- SpringBoot JWT Redis 開源知識社區系統
- CVPR2022 | 可精簡域適應
- Spring框架系列(3) - 深入淺出Spring核心之控制反轉(IOC)