如何通过反射获取 ValueType 类型的默认值
如果我有一个值类型的泛型类型参数,并且我想知道某个值是否等于默认值,我会像这样测试它:
static bool IsDefault<T>(T value){
where T: struct
return value.Equals(default(T));
}
如果我没有泛型类型参数,那么似乎我必须使用反射。如果该方法必须适用于所有值类型,那么有没有比我在这里所做的更好的方法来执行此测试? :
static bool IsDefault(object value){
if(!(value is ValueType)){
throw new ArgumentException("Precondition failed: Must be a ValueType", "value");
}
var @default = Activator.CreateInstance(value.GetType());
return value.Equals(@default);
}
顺便说一句,关于评估 Nullable 结构,我在这里没有考虑什么吗?
If I have a generic type parameter that is a value type and I want to know if a value is equal to the default I test it like this:
static bool IsDefault<T>(T value){
where T: struct
return value.Equals(default(T));
}
If I don't have a generic type parameter, then it seems like I would have to use reflection. If the method has to work for all value types, then Is there a better way to perform this test than what I am doing here? :
static bool IsDefault(object value){
if(!(value is ValueType)){
throw new ArgumentException("Precondition failed: Must be a ValueType", "value");
}
var @default = Activator.CreateInstance(value.GetType());
return value.Equals(@default);
}
On a side note, Is there anything I am not considering here with respect to evaluating Nullable structs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我发现以下扩展方法很有用并且适用于所有类型:
I have found the following extension methods useful and will work for all types:
老问题,但接受的答案对我不起作用,所以我提交这个(可能可以做得更好):
结果如下:
Old question but the accepted answer doesn't work for me so I submit this (probably can be made better):
With the following results:
我需要
ValueType
作为参数来简化:I would require
ValueType
as the parameter to simplify:是的,你错过了一些东西。通过将
object
作为参数,您需要调用代码来框Nullable
类型(将它们转换为 null 或T 值)。因此,如果您传递可为 null 的值,您的
is/throw
将抛出异常,因为null
永远不会是值类型。编辑:正如@cdhowie所说,您需要检查是否为空。这也适用于可为 Null 的类型。
Yes, you are missing something. By taking an
object
as the parameter in you are requiring calling code to boxNullable<T>
types (which converts them to null or to theirT
Value). So if you pass a nullable, youris/throw
will throw becausenull
will never be a value type.Edit: As @cdhowie said, you'll need to check for null. This will work for Nullable types as well.