在C#中检测可空类型

use*_*662 7 c# nullable

我有一个定义如下的方法:

public bool IsValid(string propertyName, object propertyValue)
{
  bool isValid = true;
  // Validate property based on type here
  return isValid;
}
Run Code Online (Sandbox Code Playgroud)

我想做的事情如下:

if (propertyValue is bool?)
{
  // Ensure that the property is true
}
Run Code Online (Sandbox Code Playgroud)

我的挑战是,我不知道如何检测我的propertyValue是否是可以为空的bool.谁能告诉我怎么做?

谢谢!

Jon*_*eet 11

propertyValue可能永远是一个Nullable<bool>.作为propertyValueis 的类型object,任何值类型都将被加框...如果你打开一个可空的值类型值,它将成为空引用或底层非可空类型的盒装值.

换句话说,你需要在不依赖价值的情况下找到类型...如果你能为我们提供更多关于你想要达到的目标的背景,我们可以帮助你.