自学内容网 自学内容网

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());
}


原文地址:https://blog.csdn.net/m0_67412019/article/details/143949044

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!