C# 中提供一个很是实用的供能,扩展方法(Extension method)ui
扩展方法是经过额外的静态方法扩展示有的类型。经过扩展方法,能够对已有类型作本身想作的相关扩展。方法:定义静态类,扩展方法也要是静态方法,而且扩展方法的第一个参数为要扩展的类型,必须附加一个this关键字。this
举例以下: spa
扩展类:code
public static class Extend { public static bool IsNullOrEmpty(this object i) { if (i == null) return true; if (i.GetType() == typeof(string)) { string temp = (string)i; return temp.IsNullOrEmpty(); } else return false; } public static Guid ToGuid(this string i) { Guid id; if (!Guid.TryParse(i, out id)) { throw new Exception(i + " can not be converted to Guid"); } return id; } }
扩展方法调用:blog
public class TestExtend { public void Test() { string i = "this a world for me"; Console.Write(i.ToGuid()); try { Guid guid = i.ToGuid(); Console.Write(guid.ToString()); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }