在C#中检测可空类型

时间:2011-06-13 13:42:53

标签: c# nullable

我有一个像这样定义的方法:

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

我想做点什么:

if (propertyValue is bool?)
{
  // Ensure that the property is true
}

我的挑战是,我不确定如何检测我的propertyValue是否是可以为空的bool。有人能告诉我怎么做吗?

谢谢!

3 个答案:

答案 0 :(得分:11)

propertyValue的值永远不会成为Nullable<bool>。由于propertyValue的类型为object,因此任何值类型都将被装箱...如果您装入可空值类型值,则它将成为空引用或基础非值的盒装值-nullable type。

换句话说,您需要在不依赖的情况下找到类型...如果您可以为我们想要实现的目标提供更多背景信息,我们可能能够帮助你更多。

答案 1 :(得分:2)

你可能需要使用泛型,但我认为你可以检查属性值的可空底层类型,如果它是bool,它是一个可以为空的bool。

Type fieldType = Nullable.GetUnderlyingType(typeof(propertyvalue));
if (object.ReferenceEquals(fieldType, typeof(bool))) {
    return true;
}

否则尝试使用通用

public bool IsValid<T>(T propertyvalue)
{
    Type fieldType = Nullable.GetUnderlyingType(typeof(T));
    if (object.ReferenceEquals(fieldType, typeof(bool))) {
        return true;
    }
    return false;
}

答案 2 :(得分:1)

这可能是一个很长的镜头,但你可以使用泛型和方法重载让编译器为你解决这个问题吗?

public bool IsValid<T>(string propertyName, T propertyValue)
{
    // ...
}

public bool IsValid<T>(string propertyName, T? propertyValue) where T : struct
{
    // ...
}

另一个想法:您的代码是否试图遍历对象上的每个属性值?如果是这样,您可以使用反射来遍历属性,并以这种方式获取它们的类型。

修改

在他的回答中使用Nullable.GetUnderlyingType作为Denis可以解决使用过载的问题。

相关问题