在C#中检测可空类型

7

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

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是否为可空布尔值。有人能告诉我该怎么做吗?

谢谢!


IsValid 是如何被调用的? - Daniel A. White
2
PropertyValue 是否总是 bool 类型或 bool 类型之一?如果是这样,您应该重载该方法,以明确两个有效类型的输入。 - The Evil Greebo
请查看 https://dev59.com/IHRC5IYBdhLWcg3wOOP1#374663。 - Lukas Winzenried
3个回答

11
propertyValue 的值永远不可能是 Nullable<bool>。由于 propertyValue 的类型是 object,任何值类型将被装箱... 如果您装箱可为空的值类型值,则它会变成 null 引用或基础非可空类型的装箱值。

换句话说,您需要找到该类型而不依赖于 ... 如果您能给我们更多上下文来解释您试图实现什么,我们也许可以为您提供更多帮助。


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;
}

1
这可能有点冒险,但你可以使用泛型和方法重载让编译器为你解决这个问题吗?
public bool IsValid<T>(string propertyName, T propertyValue)
{
    // ...
}

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

另一个想法:你的代码是否试图遍历对象上的每个属性值?如果是这样,你可以使用反射来迭代属性,并以此方式获取它们的类型。
编辑
Denis在他的答案中建议的那样使用Nullable.GetUnderlyingType将避免使用重载的需要。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接