ylbtech-LanguageSamples-SimpleVariance
生活随笔
收集整理的這篇文章主要介紹了
ylbtech-LanguageSamples-SimpleVariance
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
| ylbtech-Microsoft-CSharpSamples:ylbtech-LanguageSamples-SimpleVariance |
?
| 1.A,示例(Sample) 返回頂部 |
SimpleVariance 示例程序演示在委托和接口中使用泛型類型時,C# 4.0 對協(xié)變和逆變的支持。 在 C# 3.0 中,泛型類型是固定的。 因此,本示例在 C# 4.0 中可正常編譯,但在早期版本的 C# 中無法編譯。
程序首先聲明兩個簡單類和兩個委托:
class Animal { } class Cat : Animal { }delegate T Func1<out T>(); delegate void Action1<in T>(T a);然后,實現(xiàn)這些委托并使用這些類:
Func1<Cat> cat = () => new Cat(); Action1<Animal> act1 = (ani) => { Console.WriteLine(ani); };再進行需要協(xié)變和逆變支持的分配:
Func1<Animal> animal = cat; Action1<Cat> cat1 = act1;后面這一組分配在 C# 4.0 中可以正常工作,但在早期版本的 C# 中無法工作。 第一個分配演示協(xié)變,第二個分配演示逆變。
通過新增的上下文關(guān)鍵字 out 和 in,可以指定泛型類型是要傳遞到委托或接口方法中,還是要從委托或接口方法返回。
| 1.B,SimpleVariance 示例代碼(Sample Code)返回頂部 |
1.B.1, Program.cs
// 版權(quán)所有(C) Microsoft Corporation。保留所有權(quán)利。 // 此代碼的發(fā)布遵從 // Microsoft 公共許可(MS-PL,http://opensource.org/licenses/ms-pl.html)的條款。 // using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace SimpleVariance {class Animal { }class Cat: Animal { }class Program{// 要了解新的協(xié)變和逆變代碼能夠為您實現(xiàn)的功能// 嘗試從以下兩行代碼中添加或刪除這些內(nèi)容:delegate T Func1<out T>();delegate void Action1<in T>(T a);static void Main(string[] args){Func1<Cat> cat = () => new Cat();Func1<Animal> animal = cat;Action1<Animal> act1 = (ani) => { Console.WriteLine(ani); };Action1<Cat> cat1 = act1;Console.WriteLine(animal());cat1(new Cat());}} } View Code1.B.2,
1.B.EXE,
SimpleVariance.Cat SimpleVariance.Cat 請按任意鍵繼續(xù). . .1.B,
| 1.C,下載地址(Free Download)返回頂部 |
?
| 作者:ylbtech 出處:http://ylbtech.cnblogs.com/ 本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責(zé)任的權(quán)利。 |
轉(zhuǎn)載于:https://www.cnblogs.com/ylbtech/p/4197323.html
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的ylbtech-LanguageSamples-SimpleVariance的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 再见,2014
- 下一篇: Notepad++ NppExport: