顯示具有 OOP 標籤的文章。 顯示所有文章
顯示具有 OOP 標籤的文章。 顯示所有文章

前言:

記錄一個用到迭代、泛型及委派的好用範例,也就是我們用Linq常用到的"where方法"!



程式碼如下:

public static class Utilities
{
 public static IEnumerable<T> ToWhere<T>(this IEnumerable<T> source
      , Func<T, bool> predicate)
 {
  foreach (T item in source)
  {
   if (predicate.Invoke(item))
   {
    yield return item;
   }
  }
 }
}


實際使用 :
void Main()
{
 List<string> list = new List<string>();
 list.Add("Tom");
 list.Add("Alex");
 list.Add("Ace");

 var a = list.ToWhere(x => x.Contains("A"));
 a.Dump();
}

輸出結果:

紀錄一下同事提到的static參考變數欄位蠻容易搞混的情況。
程式碼如下:

void Main()
{
 test = new Obj1 { name = "tt" };
 test.Dump();
 
 var a = Call();
 a.Dump();
 
 a.name = "t2";
 a.Dump();
 
 //要點一
 test.Dump();
 
 a = null;
 a.Dump();
 
 //要點二
 test.Dump();
 
}

public Obj1 Call()
{
 return test;
}

public static Obj1 test;


public class Obj1
{
 public string name { get; set; }
}




主要容易搞混的點分別在程式碼上標示出來了,兩個要點:
要點一
要點一輸出結果test.name會是"t2",用Call()方法呼叫傳回的test物件在記憶體中的Heap會是同一個object這沒問題,當a.name ="t2"就將這個object改變了。

要點二
要點二要能確實判斷出它的結果,關鍵在a=null時,要知道a其實是Steak中的位址而已,只是把a這個位址指向object的關聯給斷了,並非object本身被指定為null了,因此test並不會是null。