1、DataTable.HasRows
它不属于任何框架,但通过扩展方法很容易模仿这样一个方法,它不会消除检查数据表对象是否为空或行数的原始代码,但它可以简化应用程序的代码,下面是一个代码片段:
<CODE> publicstatic bool HasRows(this DataTable dataTable) { return dataTable.IsNull() ?false: (dataTable.Rows.Count>0); } publicstatic boolIsNull(thisobjecto) { return (o==null); } Touse: If(dataTable.HasRows()) { … } </CODE> |
其它规则仍然和扩展方法相同。
2、ToTitleCase
这个方法可以将每个单词的首字母转换为大写,剩下的字母转换为小写,例如,“look below for a sample”将被转换为“Look Below For A Sample”,TextInfo是System.Globalization命名空间的一部分,但它存在以下问题:
当前的文化
如果输入字符串全部是大写
下面的扩展方法同时考虑了这两个缺陷。
<CODE> publicstaticstringToTitleCase(thisstringinputString) { return Thread.CurrentThread.CurrentCulture.TextInfo. ToTitleCase((inputString ??string.Empty).ToLower()); } </CODE> |
3、显性和隐性接口实现
这很重要吗?是的,非常重要,你知道它们之间的语法差异吗?其实它们存在根本性的区别。类上的隐性接口实现默认是一个公共方法,在类的对象或接口上都可以访问。而类上的显性接口实现默认是一个私有方法,只能通过接口访问,不能通过类的对象访问。下面是示例代码:
<CODE> INTERFACE publicinterface IMyInterface { void MyMethod(stringmyString); } CLASS THAT IMPLEMENTS THE INTERFACE IMPLICITLY publicMyImplicitClass: IMyInterface { publicvoid MyMethod(stringmyString) { /// } } CLASS THAT IMPLEMENTS THE INTERFACE EXPLICITLY publicMyExplicitClass: IMyInterface { void IMyInterface.MyMethod(stringmyString) { /// } } MyImplicitClass instance would workwitheither the classorthe Interface: MyImplicitClass myObject=newMyImplicitClass(); myObject.MyMethod(""); IMyInterface myObject =newMyImplicitClass(); myObject.MyMethod(""); MyExplicitClass would work onlywiththe interface: //The following line wouldnotwork. MyExplicitClass myObject=newMyExplicitClass(); myObject.MyMethod(""); //This will work IMyInterface myObject=newMyExplicitClass(); myObject.MyMethod(""); </CODE> |