您好,欢迎来到五一七教育网。
搜索
您的当前位置:首页C#高级:通过反射判断列表中指定字段是否存在空值

C#高级:通过反射判断列表中指定字段是否存在空值

来源:五一七教育网

1.使用

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Grade { get; set; }
}

public static void Main()
{
    // 创建一些学生对象
    var students = new List<Student>
    {
        new Student { Name = "John", Age = 20, Grade = "A" },
        new Student { Name = null, Age = 22, Grade = "B" },
        new Student { Name = "", Age = 0, Grade = "" },  // 空白字段
        new Student { Name = "Alice", Age = 21, Grade = null }
    };

    // 调用方法,检查是否有字段为空或空白
    var result = GetNotNullOrEmptyList(students, new List<string> { "Grade" }); // 排除Grade字段为空的检查

    // 输出结果
    Console.WriteLine("是否存在空值: " + result.HasNull);
    Console.WriteLine("详细分析:"+ result.Analysis);

    //是否存在空值: True
    //详细分析:列表实体序号: 2,Name的值为空或null!
    //列表实体序号: 3,Name的值为空或null!
}

2.封装 

/// <summary>
/// 判断列表字段内容是否存在NullOrWhiteSpace的情况,若有则返回出具体信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">传入待判断列表</param>
/// <param name="FeildsAllowNullList">允许为空的字段名称列表(不传默认判断所有字段)</param>
public static (bool HasNull, string Analysis) GetNotNullOrEmptyList<T>(List<T> list, List<string> FeildsAllowNullList = null) where T : class
{
    StringBuilder sb = new StringBuilder();
    bool HasNull = false;
    List<PropertyInfo> feildList = typeof(T).GetProperties().ToList();
    if (FeildsAllowNullList != null)
    {
        feildList = feildList.Where(x => !FeildsAllowNullList.Contains(x.Name)).ToList();
    }
    int index = 1;
    foreach (var entity in list)
    {
        foreach (var item in feildList)
        {
            if (string.IsNullOrWhiteSpace(item.GetValue(entity)?.ToString()))
            {
                sb.AppendLine($"列表实体序号:{index},{item.Name}的值为空或null!");
                HasNull = true;
            }
        }
        index++;
    }
    return (HasNull: HasNull, Analysis: sb.ToString());
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务