一.扩展方法:
扩展方法的行为和静态方法是非常类似的,你只能在静态类中声明它们。为声明一个扩展方法,你需要给该方法的第一个参数指定this关键字(必须这么做),如下例:
优点是:通过IntelliSense查看匿名类型,这样更容易 找到需要的功能。
// Program.cs public static class EMClass { public static int ToInt32Ext(this string s) { return Int32.Parse(s); } public static int ToInt32Static(string s) { return Int32.Parse(s); } } class Program { static void Main(string[] args) { string s = "9"; int i = s.ToInt32Ext(); // LINE A Console.WriteLine(i); int j = EMClass.ToInt32Static(s); // LINE B Console.WriteLine(j); Console.ReadLine(); } }
二.事件模板
1.定义委托和事件:
public event TPLEvent<AfterIdentityEventArgs> AfterIdentited;
(引用内部wando类库)
如果没有引用wando类库,则声明原型类似为:
在创建一个可用事件之前,首先声明一个委托,放在类的外面。(具体参加文章 基础系列之---5.C#委托和事件使用(参考)仅仅只是触发事件,不传参的做法。EventArgs.Empty)
public delegate void FileWatchEventHandler(object sender,EventArgs e);
接下来创建类FileWatch。然后声明事件,注意事件的类型即为我们之前定义的委托。
public event FileWatchEventHandler FileWatchEvent;
2.事件参数类定义:
public class AfterIdentityEventArgs : EventArgs { public DateTime ReportDate { get; set; } public bool IsMatchSuccess { get; set; } public int IdentityObject { get; set; } }
3.触发事件
if (this.AfterIdentited != null) //触发事件 this.AfterIdentited.Invoke(this, new AfterIdentityEventArgs() { IdentityObject = id, IsMatchSuccess = true, ReportDate = DateTime.Now });
4.监听该事件是否被触发,并获取事件参数内容
xx.AfterIdentited += xx_AfterIdentited;
//监听到触发了事件,接下来该做的事情。
static void xx_AfterIdentited(object sender, AfterIdentityEventArgs e) { //可以获取到e.IsMatchSuccess 的值等等。 }
三、单例模式的模板
还可以参见文章:单例模式
public class TaskStore { #region###单例模式,一个进程中只需要一个Store对象即可 public static TaskStore Instance { get { lock (locker) { return _instance; } } } private static TaskStore _instance = new TaskStore(); private static object locker = new object(); private TaskStore() { } #endregion }
三、值类型和引用类型
1.值类型:在内存中的一个地方(称为堆栈)存储它们自己和它们的内容。(结构式值类型)
2.引用类型:在内存的一个地方(称为堆)存储一个引用,而在另一个地方存储内容。(类是引用类型)
ref 关键字:一定要先赋值,out 关键字可以不用,out 常用于多值通信:例如:
MaxValue(int[] intArray,out int maxIndex)
输出数组中的最大值和该值的下标。
四、构造函数的执行顺序
1.构造函数初始化器 base 和 this 关键字的使用!