C# 委托

原文链接:https://www.cnblogs.com/ysmc/p/18800819

C# 委托(Delegate)

介绍(摘至网络)

在 C# 中,委托(Delegate) 是一种类型安全的函数指针,它允许将方法作为参数传递给其他方法

C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量,引用可在运行时被改变

委托在 C# 中非常常见,用于事件处理、回调函数、LINQ 等操作

所有的委托(Delegate)都派生自 System.Delegate 类

正文

委托,相信小伙伴们都知道这个玩意,但是很多小伙伴不知道这个东西在开发中能有什么用,我这里给小伙伴们一个方向,后续大家就可以扩散一下了

在工作中,大家应该是逃不了导出excel的,但是每有一个需求,就要写一遍重复代码,时间久了,就会自己写出一个通用的导出功能,但是只是适合简单的导出,晚上随便找个包都能解决,往往也会出现一些较为复杂的需求,例如某一个字段值根据区间给予不同的背景色,或者是需要加粗字体、给不同的字体颜色等等。

我这里就举一个例子,班级的学生成绩导出,不及格(60以下)的科目成绩给予红色背景色,一班为重点班不到80分也记为红色背景色

例子

首先我们写一个学生成绩类 student.cs

 1 public class StudentGrade
 2 {
 3     /// <summary>
 4     /// 班级
 5     /// </summary>
 6     [NotNull]
 7     [DisplayName("班级")]
 8     public string? Class { get; set; }
 9 
10     /// <summary>
11     /// 学号
12     /// </summary>
13     [NotNull]
14     [DisplayName("学号")]
15     public string? StudentId { get; set; }
16 
17     /// <summary>
18     /// 科目
19     /// </summary>
20     [NotNull]
21     [DisplayName("科目")]
22     public string? Subject { get; set; }
23 
24     /// <summary>
25     /// 成绩
26     /// </summary>
27     [NotNull]
28     [DisplayName("成绩")]
29     public double Grade { get; set; }
30 }

然后,我们来一个导出excel的函数,我比较懒,意思意思能懂就好了

 1 /// <summary>
 2 /// 导出数据到 Excel
 3 /// </summary>
 4 /// <typeparam name="T"></typeparam>
 5 /// <param name="data"></param>
 6 /// <param name="func"></param>
 7 /// <returns></returns>
 8 public async Task<Stream> ExportToExcelAsync<T>(IEnumerable<T> data, Func<string, T, CellStyle?>? func)
 9 {
10     using var package = new ExcelPackage();
11     var worksheet = package.Workbook.Worksheets.Add("StudentGrades");
12 
13     var properties = typeof(T).GetProperties();
14     // 处理表头,获取属性上的 DisplayNameAttribute 特性
15     foreach (var property in properties)
16     {
17         var index = Array.IndexOf(properties, property);
18         var attributes = property.GetCustomAttributes(typeof(DisplayNameAttribute), false) as IEnumerable<DisplayNameAttribute>;
19         if (attributes == null || !attributes.Any())
20         {
21             worksheet.Cells[1, index + 1].Value = property.Name;
22         }
23         else
24         {
25             worksheet.Cells[1, index + 1].Value = attributes.First().DisplayName;
26         }
27     }
28 
29     // 处理数据
30     for (int i = 0; i < data.Count(); i++)
31     {
32         var item = data.ElementAt(i);
33         for (int j = 0; j < properties.Length; j++)
34         {
35             var value = properties[j].GetValue(item);
36             if (func != null)
37             {
38                 var cellStyle = func(properties[j].Name, item);
39                 if (cellStyle != null)
40                 {
41                     worksheet.Cells[i + 2, j + 1].Style.Font.Color.SetColor(cellStyle.FontColor);
42                     worksheet.Cells[i + 2, j + 1].Style.Font.Size = cellStyle.FontSize;
43                     worksheet.Cells[i + 2, j + 1].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
44                     worksheet.Cells[i + 2, j + 1].Style.Fill.BackgroundColor.SetColor(cellStyle.BackgroundColor);
45                 }
46             }
47             worksheet.Cells[i + 2, j + 1].Value = value;
48         }
49     }
50 
51     return await Task.FromResult(package.Stream);
52 }

单元格样式 CellStyle

 1 public class CellStyle
 2 {
 3     /// <summary>
 4     /// 字体颜色
 5     /// </summary>
 6     public Color FontColor { get; set; }
 7 
 8     /// <summary>
 9     /// 字体大小
10     /// </summary>
11     public float FontSize { get; set; }
12 
13     /// <summary>
14     /// 背景色
15     /// </summary>
16     public Color BackgroundColor { get; set; }
17 }

这样,当你在调用通用导出的时候,由你自己处理每一个单元格的格式就好了,处理的字段columnName,以及整一行数据都给你了

 1 var data = new List<StudentGrade>
 2 {
 3     new StudentGrade { Class = "一班", StudentId = "001", Subject = "语文", Grade = 90 },
 4     new StudentGrade { Class = "一班", StudentId = "001", Subject = "数学", Grade = 80 },
 5     new StudentGrade { Class = "一班", StudentId = "001", Subject = "英语", Grade = 70 },
 6     new StudentGrade { Class = "一班", StudentId = "002", Subject = "语文", Grade = 85 },
 7     new StudentGrade { Class = "一班", StudentId = "002", Subject = "数学", Grade = 75 },
 8     new StudentGrade { Class = "一班", StudentId = "002", Subject = "英语", Grade = 65 },
 9     new StudentGrade { Class = "二班", StudentId = "003", Subject = "语文", Grade = 95 },
10     new StudentGrade { Class = "二班", StudentId = "003", Subject = "数学", Grade = 85 },
11     new StudentGrade { Class = "二班", StudentId = "003", Subject = "英语", Grade = 75 },
12     new StudentGrade { Class = "二班", StudentId = "004", Subject = "语文", Grade = 100 },
13     new StudentGrade { Class = "二班", StudentId = "004", Subject = "数学", Grade = 90 },
14     new StudentGrade { Class = "二班", StudentId = "004", Subject = "英语", Grade = 80 }
15 };
16 var cellStyle = new CellStyle
17 {
18     FontColor = Color.Black,
19     FontSize = 12,
20     BackgroundColor = Color.Red
21 };
22 var stream = await ExportToExcelAsync(data, (columnName, item) =>
23 {
24     if (columnName == "Grade" && (item.Grade < 60
25     || (item.Class == "一班" && item.Grade < 80)))
26     {
27         return cellStyle;
28     }
29     return null;
30 });
31 using var fileStream = new FileStream("StudentGrades.xlsx", FileMode.Create);
32 stream.CopyTo(fileStream);

好了,感谢大佬们的观看!

来源链接:https://www.cnblogs.com/ysmc/p/18800819

© 版权声明
THE END
支持一下吧
点赞14 分享
评论 抢沙发
头像
请文明发言!
提交
头像

昵称

取消
昵称表情代码快捷回复

    暂无评论内容