开发者

C# - How to test whether an instance is the default value for its type

开发者 https://www.devze.com 2022-12-08 09:58 出处:网络
Given an instance of an unknown reference or value type, is there any way to test whether the instance contains the default value for that type? I envisage something like this ...

Given an instance of an unknown reference or value type, is there any way to test whether the instance contains the default value for that type? I envisage something like this ...

bool IsDefaultValue(object value)
{
    return value == default(value.GetType());
}

Of course, this doesn't work because GetType returns a runtime type, but I hope 开发者_StackOverflow社区that somebody can suggest a similar technique. Thanks.


static bool IsDefaultValue<T>(T input)
{
    return Object.Equals(input, default(T));
}

Note: you can't use == for equality using generic type T.

0

精彩评论

暂无评论...
验证码 换一张
取 消