在C#中检测可空类型 [英] Detecting nullable types in C#
问题描述
我有一个像这样定义的方法:
I have a method that is defined like such:
public bool IsValid(string propertyName, object propertyValue)
{
bool isValid = true;
// Validate property based on type here
return isValid;
}
我想这样做是这样的:
I would like to do something like:
if (propertyValue is bool?)
{
// Ensure that the property is true
}
我的挑战是,我不知道如何检测我是否为PropertyValue是一个可空布尔与否。谁能告诉我如何做到这一点?
My challenge is, I'm not sure how to detect whether my propertyValue is a nullable bool or not. Can someone tell me how to do this?
感谢您!
推荐答案
为PropertyValue
可能的从不的是可空<布尔>
。由于为PropertyValue
的类型是对象
,任何值类型将被装箱......如果你框可空类型值,就成了无论是空引用,或潜在的非可空类型的装箱值。
The value of propertyValue
could never be a Nullable<bool>
. As the type of propertyValue
is object
, any value types will be boxed... and if you box a nullable value type value, it becomes either a null reference, or the boxed value of the underlying non-nullable type.
在换句话说,你需要找到的类型不依托的值的...如果你可以给我们更多的上下文你想达到什么样的,我们也许能够帮助你。
In other words, you'd need to find the type without relying on the value... if you can give us more context for what you're trying to achieve, we may be able to help you more.
这篇关于在C#中检测可空类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!