C# 知识点小记

in Code with 0 comment

NPOI 导入 Excel 日期数字值转换为 DateTime

使用 NPOI 读取 Excel 日期类型值时,获取到的数据是数字类型,需要转换为 DateTime,这就需要使用到 DateTime.FromOADate(Double) 方法,代码示例如下:

public static DateTime? ConvertExcelDateToDateTime(this string columnValue)
{
    if (string.IsNullOrWhiteSpace(columnValue))
    {
        return null;
    }
    if (DateTime.TryParse(columnValue, out DateTime date))
    {
        return date;
    }
    if (double.TryParse(columnValue, out double doubleDate))
    {
        return DateTime.FromOADate(doubleDate);
    }
    return null;
}

自定义类型实例去重

自定义类实例比较是否相同,需要重写 EqualsGetHastCode 方法。

假设有一个 Person 类,有 姓名性别年龄 三个属性,姓名性别 决定数据的唯一性。

class Person
{
    public Person(
        string name,
        bool gender,
        int age)
    {
        Name = name;
        Gender = gender;
        Age = age;
    }

    public string Name { get; set; }

    public bool Gender { get; set; }

    public int Age { get; set; }

    public override bool Equals(object obj)
    {
        if (obj is Person person)
        {
            return Name == person.Name && Gender == person.Gender;
        }
        return false;
    }

    public override int GetHashCode()
    {
        return $"{Name}{Gender}".GetHashCode();
    }
}

现在要对用户列表去重,示例代码如下:

void Main()
{
    List<Person> persons = new()
    {
        new Person("Marry", false, 12),
        new Person("Bob", true, 16),
        new Person("Marry", false, 15),
    };
    Console.WriteLine(persons.Distinct().Count()); // 2
}

判断一个类型是否为泛型集合

public static bool IsListType(this Type type)
{
    return type.IsGenericType
        && (type.GetGenericTypeDefinition() == typeof(List<>));
}
使用场景,可以用在反射类中属性是否为泛型集合,进而遍历集合。
Comments are closed.