导读:
众所周知,dll是封装好的类库,里面的代码是没办法修改的。但我们又想在原来的代码基础上增加一些自定义方法,应该怎么做呢?下面就让我们一起来学习一下 “如何给类添加扩展方法?”
步骤:
一、举例,我这里有一个EPPlus.dll类库,主要用来读取Excel表格数据的,在这个EPPlus.dll类库里的OfficeOpenXml命名空间下,有一个ExcelRangeRow类,这个ExcelRangeRow类的代码如下:
#region 程序集 EPPlus.dll, v4.0.30319
#endregion
using OfficeOpenXml.Style;
using System;
using System.Collections;
using System.Collections.Generic;
namespace OfficeOpenXml
{
public class ExcelRangeRow : IEnumerable<ExcelRangeRow>, IEnumerable, IEnumerator<ExcelRangeRow>, IDisposable, IEnumerator
{
public bool Collapsed { get; set; }
public ExcelRangeRow Current { get; }
public bool CustomHeight { get; set; }
public int EndRow { get; }
public double Height { get; set; }
public bool Hidden { get; set; }
public int OutlineLevel { get; set; }
public bool PageBreak { get; set; }
public bool Phonetic { get; set; }
public ExcelRangeBase Range { get; }
public int StartRow { get; }
public ExcelStyle Style { get; }
public int StyleID { get; set; }
public string StyleName { get; set; }
public void Dispose();
public IEnumerator<ExcelRangeRow> GetEnumerator();
public bool MoveNext();
public void Reset();
}
}
二、现在我要给ExcelRangeRow类添加一些扩展方法,首先创建一个静态类ExpandClass.cs(类名自定义),这个静态类你放在什么位置都可以,具体代码如下:
为什么是创建静态类?
因为静态类在程序启动时,就会自动加载到内存中,供程序调用。
特别说明:
扩展方法也必须是静态的,在方法的第一个参数要写 this [类名] [自定义名称] ,表示是哪个类的扩展方法,这点非常关键。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OfficeOpenXml;
namespace testSystem
{
/// <summary>
/// 给DLL类库里的类,添加扩展方法
/// 方法:首先要创建一个静态类,扩展方法也要是静态的,在方法的第一个参数要写this 类名 自定义名称,表示是哪个类的扩展方法。
/// </summary>
public static class ExpandClass
{
public static ExcelRange Cell(this ExcelRangeRow row, int column)
{
return row.Range.Worksheet.Cells[row.StartRow, column];
}
public static float GetFloat(this ExcelRange cell)
{
return cell.GetValue<float>();
}
public static int GetInt(this ExcelRange cell)
{
return cell.GetValue<int>();
}
public static string GetString(this ExcelRange cell)
{
return cell.GetValue<string>();
}
}
}
三、这样我们就可以直接调用这些扩展方法了,如下:
public void getDataFromExcel(ExcelRangeRow row){
this.id = row.Cell(1).GetInt();
this.name = row.Cell(2).GetString();
this.age = (row.Cell(3).GetString());
this.sex = row.Cell(4).GetFloat();
}