C# 判断泛型中参数是结构体是否为默认值的方法

2022年4月3日 2132点热度 2人点赞 0条评论
内容纲要

第一种:

    private bool IsDefaultValue(T value)
    {
        Span<byte> valueBytes = MemoryMarshal.AsBytes<T>(new T []{ value }.AsSpan());
        var defaultBytes = new byte[valueBytes.Length];
        return valueBytes.SequenceEqual(defaultBytes);
    }

第二种:

public class Test<T> where T : struct, IComparable
{
    public T Id { get; private set; }
    public Test(T id)
    {
        Id = id;
    }

    public bool IsDefault()
    {
        return Id.CompareTo(0) == 0;
    }
}

第三种:

public class Test<T> where T : struct, IComparable<T>
{
    private readonly static T defaultValue;
    static Test()
    {
        defaultValue = new T();
    }
    public T Id { get; private set; }
    public Test(T id)
    {
        Id = id;
    }

    public bool IsDefault()
    {
        return Id.CompareTo(defaultValue) == 0;
    }

痴者工良

高级程序员劝退师

文章评论