C#中代码重构方法例子
自从C#3.0的扩展方法出来后,在我做的框架里的曾经的类似XXXUtil的类,全部可以用扩展方法来实现了。而且原来的调用方式依然兼容。举例来说:
public static Object[] ArrayListToObjectArray(this ArrayList al)
其实,我就在方法要扩展的对象加this,而我本身我的类StringUtil本身又是static的,所以两种调用方式兼容。
用法一:(注意,这是扩展方法用法)
[TestMethod] var al = new ArrayList {"Lihua", 26}; var s = al.ArrayListToStringArray(); if (s.Length == 2 && s[0] == "Lihua" && s[1] == "26") { return TestResult.Fail; |
[TestMethod] var al = new ArrayList {"Lihua", 26}; var s = StringUtil.ArrayListToStringArray(al); if (s.Length == 2 && s[0] == "Lihua" && s[1] == "26") { }
|