【问题标题】:Detecting nullable types in C#在 C# 中检测可空类型
【发布时间】:2011-06-13 22:20:22
【问题描述】:

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

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 怎么叫?
  • PropertyValue 是否总是 bool 类型或 bool 类型?如果是这样,您应该重载该方法以明确传入的两个有效类型。

标签: c# nullable


【解决方案1】:

propertyValue 的值可能永远Nullable<bool>。由于propertyValue 的类型是object,任何值类型都将被装箱......如果你装箱一个可为空的值类型值,它要么成为空引用,要么成为底层不可为空类型的装箱值。

换句话说,您需要在不依赖 的情况下找到类型...如果您可以为我们提供更多关于您要实现的目标的上下文,我们也许可以为您提供更多帮助。

【讨论】:

    【解决方案2】:

    您可能需要为此使用泛型,但我认为您可以检查 propertyvalue 的可为空的基础类型,如果它是 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;
    }
    

    【讨论】:

      【解决方案3】:

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

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

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

      编辑

      在他的回答中建议使用Nullable.GetUnderlyingType 作为Denis 将绕过使用重载的需要。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-12
        • 1970-01-01
        • 2022-08-02
        • 2017-10-22
        • 2011-06-27
        • 2021-02-17
        • 2021-05-02
        相关资源
        最近更新 更多