好处:不需要继承,对现有类型进行扩展
public static class ExtString { public static string myTest(this String str) { return "[" + str + "]"; } public static DataRow Expect(this DataRow dr, string fieldName) { if (dr != null) { DataTable newDt = dr.Table; newDt.Columns.Remove(fieldName); DataRow newDr = newDt.NewRow(); foreach (DataColumn dc in dr.Table.Columns) { if (!dc.ColumnName.Equals(fieldName)) { newDr[dc.ColumnName] = dr[dc.ColumnName]; } } return newDr; } return null; } }
使用举例:
string m1 = "ddd"; MessageBox.Show(m1.myTest()); DataTable dt = new DataTable(); dt.Columns.Add("TID", typeof(int)); dt.Columns.Add("Flg", typeof(int)); dt.Columns.Add("TName", typeof(string)); DataRow dr = dt.NewRow(); dr["TID"]=1; dr["Flg"] = 1; dr["TName"] = "testaa"; //dt.Rows.Add(dr); DataRow dr1 = dr.Expect("Flg");
泛型类的扩展方法:
public static class DataContractExtensions { //测试方法 public static T Test<T>(this T instance) where T : Test2 { T Res = default(T); try { Res.AttrTest = instance.AttrTest.Substring(0,2); //其他复杂逻辑... } catch { } return Res; } } public class Test2 { public string AttrTest { set; get; } }