A.dynamic
1 public class dynamicDemo 2 { 3 public static void Test() 4 { 5 dynamic d = 100; 6 d += 10; 7 Console.WriteLine(d.GetType()+" +=10 Result:\t"+d); 8 d = 1.200; 9 d += 10;10 Console.WriteLine(d.GetType() + " +=10 Result:\t" + d);11 d = "string";12 d += 10;13 Console.WriteLine(d.GetType() + " +=10 Result:\t" + d);14 }15 }
B.可选(或默认)参数 ,命名参数
public class DefaultParmDemo { //可选(或默认)参数:y/z public void Add(int x, int y = 10, int z = 100) { Console.WriteLine(string.Format("x({0})+y({1})+z({2})=Sum({3})",x,y,z,x+y+z)); } public static void Test() { DefaultParmDemo demo=new DefaultParmDemo(); demo.Add(5); demo.Add(5, 5); demo.Add(5, z: 10); demo.Add(5, z: 10, y: 15); //命名参数:方法定义的参数顺序与方法调用时的参数顺序可以不一致 } }
C.Lazy<T>
[使用场景]
i.当创建一个对象的子对象开销比较大时,而且有可能在程序中用不到这个子对象, 那么可以考虑用延迟加载的方式来创建子对象。 ii.另外一种情况就是当程序一启动时,需要创建多个对象,但仅有几个对象需要立即使用, 这样就可以将一些不必要的初始化工作延迟到使用时,这样可以非常有效的提高程序的启动速度。DataExample:
View Code
1 public class DataExample 2 { 3 public string Title 4 { 5 get; 6 set; 7 } 8 public static ListGetExampleList() 9 {10 List examples = new List { 11 new DataExample{Title="Lazy Load"},12 new DataExample{Title="Delegate"},13 new DataExample{Title="Event"},14 new DataExample{Title="Thread"}15 };16 return examples;17 }18 public static List > GetLazyExampleList()19 {20 List > examples=new List >{ 21 new Lazy (()=>new DataExample{Title="Lazy Load"}),22 new Lazy (()=> new DataExample{Title="Delegate"}),23 new Lazy (()=>new DataExample{Title="Event"}),24 new Lazy (()=>new DataExample{Title="Thread"})25 };26 return examples;27 }28 }
1 public class LazyDemo 2 { 3 4 public Lazy
> DataExampleA 5 { 6 get; 7 private set; 8 } 9 public List > DataExampleB10 {11 get;12 private set;13 }14 15 // 第一次引用时加载16 private List _dataExampleC;17 public List DataExampleC18 {19 get20 {21 if (_dataExampleC==null)22 {23 _dataExampleC = DataExample.GetExampleList();24 }25 return _dataExampleC;26 }27 }28 public LazyDemo()29 {30 31 //多个对象不一定都用到时32 DataExampleA = new Lazy
>( () => DataExample.GetExampleList()); 33 DataExampleB = DataExample.GetLazyExampleList();34 35 36 }37 public override string ToString()38 {39 40 Console.WriteLine("A IsValueCreated:" +DataExampleA.IsValueCreated);41 int i=0;42 foreach (var item in this.DataExampleB)43 { 44 Console.WriteLine("B Item IsCreated: " +item.IsValueCreated+"\tTitle:"+item.Value.Title); 45 if (i++>0)46 break;47 }48 Console.WriteLine();49 foreach (var item in this.DataExampleB)50 {51 Console.WriteLine("B Item IsCreated: " + item.IsValueCreated + "\tTitle:" + item.Value.Title); 52 }53 54 Console.WriteLine("A IsValueCreated:" +DataExampleA.IsValueCreated);55 return base.ToString();56 }57 58 public static void Test()59 {60 //延迟加载61 LazyDemo blogUser = new LazyDemo();62 blogUser.ToString();63 }64 }