在C#中用静态类来扩展类的方法
1.待扩展类
private IList<Person> _personList;
[SetUp]
public void Setup()
{
_personList = new List<Person>();
_personList.Add(new Person() { FirstName="Daniel", LastName = "Day-Lewis", YearBorn = 1957 });
_personList.Add(new Person() { FirstName = "Sally", LastName = "Field", YearBorn = 1946 });
_personList.Add(new Person() { FirstName = "David", LastName = "Strathairn", YearBorn = 1949 });
_personList.Add(new Person() { FirstName = "Joseph", LastName = "Gordon-Levitt", YearBorn = 1981 });
_personList.Add(new Person() { FirstName = "James", LastName = "Spader", YearBorn = 1960 });
}
从上面代码看出其通过接口IList定义为List类型。
2.用于扩展的静态类中的静态方法
public static class Extensions
{
/// <summary>
/// creates an epplus worksheet from a list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="rows"></param>
/// <param name="name"></param>
/// <returns></returns>
public static ExtensionWorksheet<T> ToWorksheet<T>(this IList<T> rows, string name, Action<ExcelColumn> configureColumn = null, Action<ExcelRange> configureHeader = null, Action<ExcelRange> configureHeaderRow = null, Action<ExcelRange, T> configureCell = null)
{
var worksheet = new ExtensionWorksheet<T>()
{
Name = name,
Workbook = new ExtensionWorkbook(),
Rows = rows,
Columns = new List<ExtensionColumn<T>>(),
ConfigureHeader = configureHeader,
ConfigureColumn = configureColumn,
ConfigureHeaderRow = configureHeaderRow,
ConfigureCell = configureCell
};
return worksheet;
}
}
this IList
3 静态扩展方法的调用
var package = _personList.ToWorksheet("Actors");
4 适用场景
很多时候作用效果跟lambda(拉姆达)表达式很类似。就是需要传入很多参数,或者需要调用很多方法的时候。代码会变得很多,可读性会变差,可操作性也会变复杂,扩展性会变差。比如当操作EXCEL导出的时候,样式会有方法,Mapper数据库会有方法,保存会有方法,传入worksheet会有方法,传入标题会有方法,用了静态类扩展为list的方法,可读性会很好,可扩展性好,操作性佳。如果不这么操作,缺点就是需要示例化多个对象方法,然后原生的excel对象还需要在这几个不同对象的方法之间传递,非常的不方便。
如下示例
var bytes = yourListOfT.ToWorksheet("Title", configureHeader: f =>
{
f.Style.Fill.PatternType = ExcelFillStyle.Solid;
f.Style.Fill.BackgroundColor.SetColor(blue);
f.Style.Font.Color.SetColor(Color.White);
f.Style.Font.Name = "Tahoma";
f.Style.Font.Bold = true;
f.Style.Font.Size = 10;
f.Style.VerticalAlignment = ExcelVerticalAlignment.Top;
f.Style.WrapText = true;
}, configureColumn: f => f.AutoFit())
.ToXlsx();
5 小结
在C#中用静态类来扩展类的方法,非常实用于代码的封装,以后要尽可能地多用这个技巧。