C#迭代器、装箱/拆箱、重载等
迭代器
迭代器是什么?
迭代器是作為一個容器,將要遍歷的數(shù)據(jù)放入,通過統(tǒng)一的接口返回相同類型的值。
為什么要用迭代器?
為何了為集合提供統(tǒng)一的遍歷方式,迭代器模式使得你能夠獲取到序列中的所有元素而不用關(guān)心是其類型,如果沒有迭代器,某些數(shù)據(jù)結(jié)構(gòu)遍歷較為困難,如Map無法迭代
如果一個類實現(xiàn)了IEnumerable接口,那么就能夠被迭代,才能使用foreach
迭代器概述
- 迭代器是可以返回相同類型的值的有序序列的一段代碼。
- 迭代器可用作方法、運算符或?get?訪問器的代碼體。
- 迭代器代碼使用?yield return?語句依次返回每個元素。yield break?將終止迭代。
- 可以在類中實現(xiàn)多個迭代器。每個迭代器都必須像任何類成員一樣有唯一的名稱,并且可以在?foreach?語句中被客戶端代碼調(diào)用,如下所示:foreach(int x in SampleClass.Iterator2){}
- 迭代器的返回類型必須為?IEnumerable、IEnumerator、IEnumerable<T> 或?IEnumerator<T>。
yield?關(guān)鍵字用于指定返回的值。到達(dá)?yield return?語句時,會保存當(dāng)前位置。下次調(diào)用迭代器時將從此位置重新開始執(zhí)行
如何使用迭代器
?
public System.Collections.IEnumerator GetEnumerator() {for (int i = 0; i < max; i++){yield return i;} }?
//為整數(shù)列表創(chuàng)建迭代器 public class SampleCollection{public int[] items = new int[5] { 5, 4, 7, 9, 3 };public System.Collections.IEnumerable BuildCollection() {for (int i = 0; i < items.Length; i++) {yield return items[i];}}} class Program {static void Main(string[] args) {SampleCollection col = new SampleCollection();foreach (int i in col.BuildCollection())//輸出集合數(shù)據(jù) {System.Console.Write(i + " ");}for (;;) ;}}
?
?
類型比較
封箱和拆箱子:封箱是把值類型轉(zhuǎn)換為System.Object,或者轉(zhuǎn)換為由值類型的接口類型。拆箱相反。
裝箱和拆箱是為了將值轉(zhuǎn)換為對象
struct MyStruct{public int Val;}class Program{static void Main(string[] args) {MyStruct valType1 = new MyStruct();valType1.Val = 1;object refType = valType1;//封箱操作,可以供傳遞用MyStruct valType2 = (MyStruct)refType;//訪問值類型必須拆箱Console.WriteLine(valType2.Val);//輸出1for (;;) ;}Is運算符語法:
<operand>is<type>同類型返回true,不同類型返回false
As運算符語法:
<operand>is<type>把一種類型轉(zhuǎn)換為指定的引用類型
?
運算符重載
public class Add2 {public int val {get; set;}public static Add2 operator ++(Add2 op1) {op1.val = 100;//設(shè)置屬性op1.val = op1.val + 2;return op1;}} class Program {static void Main(string[] args) {Add2 add = new Add2();add++;Console.WriteLine(add.val);//輸出102for (;;) ;}}?
轉(zhuǎn)載于:https://www.cnblogs.com/feichangnice/p/5251731.html
總結(jié)
以上是生活随笔為你收集整理的C#迭代器、装箱/拆箱、重载等的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: wordpress插入腾讯视频的方法
- 下一篇: UITextView实现图文混排效果