c# 根据泛型返回任意类型 电脑版发表于:2023/2/23 10:17 注意通过这种方式,类型要能转化成功才行,不然会报类型转化的错误的 ``` /// <summary> /// 根据传递过来的泛型来获取对应的类型数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="hSSFCell"></param> /// <returns></returns> private T GetCellValue<T>(NPOI.SS.UserModel.ICell hSSFCell) { Type t = typeof(T); if (hSSFCell == null) { return default(T); } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.Numeric) { // NPOI中数字和日期都是NUMERIC类型的,这里对其进行判断是否是日期类型 if (NPOI.SS.UserModel.DateUtil.IsCellDateFormatted(hSSFCell)) { return (T)(object)hSSFCell.DateCellValue; } return (T)(object)hSSFCell.NumericCellValue; } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.String) { return (T)(object)hSSFCell.StringCellValue; } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.Boolean) { return (T)(object)hSSFCell.BooleanCellValue; } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.Blank) { return default(T); } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.Error) { return (T)(object)hSSFCell.ErrorCellValue; } return default(T); } ```