ASP.NET泛型三之使用協(xié)變和逆變實(shí)現(xiàn)類型轉(zhuǎn)換
".NET泛型"系列:
協(xié)變(Convariant)和逆變(Contravariant)的出現(xiàn),使數(shù)組、委托、泛型類型的隱式轉(zhuǎn)換變得可能。 子類轉(zhuǎn)換成基類,稱之為協(xié)變;基類轉(zhuǎn)換成子類,稱之為逆變。.NET4.0以來,支持了泛型接口的協(xié)變和逆變。
泛型協(xié)變
如果子類泛型隱式轉(zhuǎn)換成基類泛型,使用泛型協(xié)變。
有這樣的2個基類和派生類。
public class Animal
{
public virtual void Write()
{
Console.WriteLine("我是基類");
}
}
public class Dog : Animal
{
public override void Write()
{
Console.WriteLine("我是小小狗");
}
}
為了讓派生類Dog隱式轉(zhuǎn)換成基類Animal,先定義支持協(xié)變的泛型接口。
//支持協(xié)變的接口
public interface IFactory<out T>
{
T Create();
}
再實(shí)現(xiàn)這個接口。
public class Factory<T> : IFactory<T>
{
public T Create()
{
return (T)Activator.CreateInstance<T>();
}
}
客戶端調(diào)用。
class Program
{
static void Main(string[] args)
{
IFactory<Dog> dogFactory = new Factory<Dog>();
IFactory<Animal> animalFactory = dogFactory; //協(xié)變
Animal animal = animalFactory.Create();
animal.Write();
Console.ReadKey();
}
}
運(yùn)行輸出:我是小小狗
以上,我們可以看出:
- 協(xié)變后,父類的方法完全由子類替代,父類原先的方法不復(fù)存在
- 泛型接口中的out關(guān)鍵字必不可少
泛型逆變
關(guān)于通知的一個接口。
public interface INotification
{
string Message { get; }
}
關(guān)于通知接口的抽象實(shí)現(xiàn)。
public abstract class Notification : INotification
{
public abstract string Message { get; }
}
關(guān)于通知抽象類的具體實(shí)現(xiàn)。
public class MailNotification : Notification
{
public override string Message
{
get { return "你有郵件了~~"; }
}
}
接下來,需要把通知的信息發(fā)布出去,需要一個發(fā)布通知的接口INotifier,該接口依賴INotification,大致INotifier<INotification>,而最終顯示通知,我們希望INotifier<MailNotification>,INotifier<INotification>轉(zhuǎn)換成INotifier<MailNotification>,這是逆變,需要關(guān)鍵字in。
public interface INotifier<in TNotification> where TNotification : INotification
{
void Notify(TNotification notification);
}
實(shí)現(xiàn)INotifier。
public class Notifier<TNotification> : INotifier<TNotification> where TNotification : INotification
{
public void Notify(TNotification notification)
{
Console.WriteLine(notification.Message);
}
}
客戶端調(diào)用。
class Program
{
static void Main(string[] args)
{
INotifier<INotification> notifier = new Notifier<INotification>();
INotifier<MailNotification> mailNotifier = notifier;//逆變
mailNotifier.Notify(new MailNotification());
Console.ReadKey();
}
}
運(yùn)行輸出:你有郵件了~~
以上,我們可以看出:
- INotifier的方法Notify()的參數(shù)類型是INotification,逆變后把INotification類型參數(shù)隱式轉(zhuǎn)換成了實(shí)現(xiàn)類MailNotificaiton。
- 泛型接口中的in關(guān)鍵字必不可少
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章:
1. 如何將asp.net core程序部署到Linux服務(wù)器2. ASP.NET MVC獲取多級類別組合下的產(chǎn)品3. ASP.NET MVC前臺動態(tài)添加文本框并在后臺使用FormCollection接收值4. ASP.NET堆和棧三之引用類型對象拷貝和內(nèi)存分配5. ASP.NET泛型二之泛型的使用方法6. ASP.Net Core對USB攝像頭進(jìn)行截圖7. 使用HttpClient增刪改查ASP.NET Web API服務(wù)8. 如何使用ASP.NET Core 配置文件9. ASP.NET MVC實(shí)現(xiàn)單個圖片上傳、限制圖片格式與大小并在服務(wù)端裁剪圖片10. asp.net生成HTML

網(wǎng)公網(wǎng)安備