【问题标题】:How to check if an object is nullable?如何检查一个对象是否可以为空?
【发布时间】:2008-12-17 14:17:16
【问题描述】:

如何检查给定对象是否可以为空,换句话说如何实现以下方法...

bool IsNullableValueType(object o)
{
    ...
}

我正在寻找可为空的值类型。我没有想到引用类型。

//Note: This is just a sample. The code has been simplified 
//to fit in a post.

public class BoolContainer
{
    bool? myBool = true;
}

var bc = new BoolContainer();

const BindingFlags bindingFlags = BindingFlags.Public
                        | BindingFlags.NonPublic
                        | BindingFlags.Instance
                        ;


object obj;
object o = (object)bc;

foreach (var fieldInfo in o.GetType().GetFields(bindingFlags))
{
    obj = (object)fieldInfo.GetValue(o);
}

obj 现在指的是 bool (System.Boolean) 类型的对象,其值等于 true。我真正想要的是Nullable<bool>

类型的对象

所以现在作为一种解决方法,我决定检查 o 是否可以为空,并在 obj 周围创建一个可以为空的包装器。

【问题讨论】:

  • 代码是否应该包含可以为空的字符串?它们是似乎可以为空的非泛型 ValueType。还是它们不是 ValueType?
  • String 不是 ValueType。它是一个引用类型。
  • 这是一个非常好的问题! 'Type.IsNullableType()' 有点欺骗,因为它实际上只检查类型是 'Nullable',如果你真的想检查任何可以接受 null 的类型,它不会返回预期的结果值(例如,我尝试与 a.IsNullableType() 一起使用,其中 'a' 是在运行时确定的 'typeof(string)')
  • 答案在 fieldInfo.FieldType 中:检查 FieldType 是否为泛型,泛型是否为 Nullable 类型。 (例如:if (FieldType.IsGenericType && FieldType.GetGenericTypeDefinition() == typeof(Nullable)))。不要尝试获取 obj.GetType() 它将具有 Nullable 变量 T 的 UndelyingSystemType(在您的布尔类型的情况下,而不是 Nullable),这是一个装箱问题。

标签: c# .net nullable


【解决方案1】:

有两种可空类型 - Nullable<T> 和引用类型。

Jon 纠正了我,如果装箱很难输入类型,但您可以使用泛型: - 那么下面怎么样。这实际上是在测试类型 T,但使用 obj 参数纯粹用于泛型类型推断(以便于调用) - 但是,如果没有 obj 参数,它的工作原理几乎相同。

static bool IsNullable<T>(T obj)
{
    if (obj == null) return true; // obvious
    Type type = typeof(T);
    if (!type.IsValueType) return true; // ref-type
    if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
    return false; // value-type
}

但如果您已经将值装箱到对象变量中,这将不会那么好。

微软文档:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/how-to-identify-a-nullable-type

【讨论】:

  • 最后一行只有在你设法得到一个装箱的 Nullable 而不是直接装箱到 T 时才有效。这是可能的,但从我记得的情况来看很难实现。
  • 这段代码对我很有帮助,不是因为我得到了一个盒装的 Nullable 而是因为我正在编写一个通用的 WPF 转换器基类并且一些属性是可以为空的,所以我使用 Nullable.GetUnderlyingType 来检测这种情况和 Activator.CreateInstance 使盒装的可为空,(Convert.ChangeType 不处理可为空的 btw)。
  • @Abel 如果您的意思是重新编辑以澄清他没有考虑引用类型,我认为我的回答早于该编辑;我怀疑,读者可以根据自己的需要在那里做出自己的决定(确认:他的评论 re ref-types 于 14:42 添加;我的回答都是
  • 当 obj = 1 时 (obj == null) 会抛出异常吗?
  • @JustinMorgan 如果T 是受T : struct 约束的泛型参数,则T 不允许为Nullable&lt;&gt;,因此在这种情况下无需检查!我知道 Nullable&lt;&gt; 类型是一个结构,但在 C# 中,约束 where T : struct 专门排除可空值类型。规范说:“请注意,虽然归类为值类型,但可为空的类型(第 4.1.10 节)不满足值类型约束。”
【解决方案2】:

使用方法重载有一个非常简单的解决方案

http://deanchalk.com/is-it-nullable/

摘录:

public static class ValueTypeHelper
{
    public static bool IsNullable<T>(T t) { return false; }
    public static bool IsNullable<T>(T? t) where T : struct { return true; }
}

然后

static void Main(string[] args)
{
    int a = 123;
    int? b = null;
    object c = new object();
    object d = null;
    int? e = 456;
    var f = (int?)789;
    bool result1 = ValueTypeHelper.IsNullable(a); // false
    bool result2 = ValueTypeHelper.IsNullable(b); // true
    bool result3 = ValueTypeHelper.IsNullable(c); // false
    bool result4 = ValueTypeHelper.IsNullable(d); // false
    bool result5 = ValueTypeHelper.IsNullable(e); // true
    bool result6 = ValueTypeHelper.IsNullable(f); // true

【讨论】:

  • 加一个给你先生添加测试用例。我已经使用这些测试用例来检查所有其他答案。更多的人应该多做一点。
  • 不管怎样,这在 VB.NET 中是行不通的。在将返回 True 的所有情况下,它都会导致编译器错误“重载解析失败,因为没有可访问的 'IsNullable' 最适合这些参数”。
  • 我真的很喜欢这个解决方案 - 很遗憾 VB 无法处理它。我尝试使用 ValueType 解决问题,但遇到了问题,VB 编译器根据它是作为共享方法还是扩展调用而对使用哪个重载不一致,我什至提出了一个问题,因为它看起来很奇怪:stackoverflow.com/questions/12319591/…
  • 您正在检查 compile-time 类型,但如果编译时类型可以为空 (System.Nullable&lt;&gt;),这已经很明显了(来自智能感知)。如果你说object g = e;然后ValueTypeHelper.IsNullable(g),你期望得到什么?
  • 我刚刚验证过; 这不起作用,正如 Jeppe 所说。如果将变量强制转换为对象,它将始终返回 false。因此,您无法通过这种方式在运行时确定未知对象的类型。唯一有效的情况是类型在编译时是固定的,在这种情况下,您根本不需要运行时检查。
【解决方案3】:

这对我有用,而且看起来很简单:

static bool IsNullable<T>(T obj)
{
    return default(T) == null;
}

对于值类型:

static bool IsNullableValueType<T>(T obj)
{
    return default(T) == null && typeof(T).BaseType != null && "ValueType".Equals(typeof(T).BaseType.Name);
}

【讨论】:

  • 为了它的价值,这也是测试used by Microsoft
  • 很好......这不是最佳答案,因为它后来出现了吗?我发现最佳答案令人困惑。
  • 这应该是最佳答案。经过几天尝试不同的方法后,我随机想到了这个解决方案,尝试了一下,它似乎工作得很好(与评分最高的答案相比)
  • 这是找出是否可以将任何实例设置为 NULL 的绝佳解决方案,但是对于可以设置为 null 的 所有内容(包括普通对象),它将返回 true。重要的是要意识到最初的问题是特别想检测 Nullable ValueTypes。
  • 微软使用的地址现在this line
【解决方案4】:

“如何检查一个类型是否可以为空?”的问题实际上是“如何检查一个类型是否是Nullable&lt;&gt;?”,可以概括为“如何检查一个类型是否是某个泛型类型的构造类型?”,这样它不仅回答了“是@ 987654322@ a Nullable&lt;&gt;?”,还有“List&lt;int&gt;List&lt;&gt;?”。

提供的大多数解决方案都使用Nullable.GetUnderlyingType() 方法,这显然只适用于Nullable&lt;&gt; 的情况。我没有看到适用于任何泛型类型的通用反射解决方案,因此我决定在此处添加它以供后代使用,即使这个问题很久以前就已经得到解答。

要使用反射检查类型是否为某种形式的Nullable&lt;&gt;,首先必须将构造的泛型类型(例如Nullable&lt;int&gt;)转换为泛型类型定义Nullable&lt;&gt;。您可以使用Type 类的GetGenericTypeDefinition() 方法来做到这一点。然后,您可以将结果类型与Nullable&lt;&gt; 进行比较:

Type typeToTest = typeof(Nullable<int>);
bool isNullable = typeToTest.GetGenericTypeDefinition() == typeof(Nullable<>);
// isNullable == true

同样适用于任何泛型:

Type typeToTest = typeof(List<int>);
bool isList = typeToTest.GetGenericTypeDefinition() == typeof(List<>);
// isList == true

几种类型可能看起来相同,但不同数量的类型参数意味着它是完全不同的类型。

Type typeToTest = typeof(Action<DateTime, float>);
bool isAction1 = typeToTest.GetGenericTypeDefinition() == typeof(Action<>);
bool isAction2 = typeToTest.GetGenericTypeDefinition() == typeof(Action<,>);
bool isAction3 = typeToTest.GetGenericTypeDefinition() == typeof(Action<,,>);
// isAction1 == false
// isAction2 == true
// isAction3 == false

由于Type 对象每个类型都会实例化一次,因此您可以检查它们之间的引用相等性。所以如果你想检查两个对象是否属于同一个泛型类型定义,你可以这样写:

var listOfInts = new List<int>();
var listOfStrings = new List<string>();

bool areSameGenericType =
    listOfInts.GetType().GetGenericTypeDefinition() ==
    listOfStrings.GetType().GetGenericTypeDefinition();
// areSameGenericType == true

如果您想检查一个对象是否可以为空,而不是 Type,那么您可以将上述技术与 Marc Gravell 的解决方案一起使用来创建一个相当简单的方法:

static bool IsNullable<T>(T obj)
{
    if (!typeof(T).IsGenericType)
        return false;

    return typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>);
}

【讨论】:

  • @AllonGuralnek 我的回答中有简化版本。我想把它作为编辑,因为我的声誉不是你的水平,所以在你的答案上没有我的名字就会被编辑,即便如此,评论似乎总是让我陷入困境,即使它是作者也是如此不是。奇怪的世界,有些人不懂定义:)。
  • @ipavlu:您的版本没有简化,实际上更复杂。我认为您的意思是它已优化,因为您缓存了结果。这使得它更难理解。
  • @AllonGuralnek 静态泛型类和静态一次性初始化字段,复杂吗?亲爱的上帝,我犯下了可怕的罪行:)。
  • @ipavku:是的,因为它与“如何检查对象是否可以为空?”这个问题无关。我尽量保持简单和重点,避免引入不必要和不相关的概念。
  • @nawfal:如果我理解正确的话,你在面对框架已经提供的Nullable.GetUnderlyingType() 的存在时质疑我的实现。为什么不直接使用框架中的方法呢?嗯,你应该。它更清晰,更简洁,经过更好的测试。但是在我的帖子中,我试图教如何使用反射来获取您想要的信息,以便有人可以将其应用于任何类型(通过将typeof(Nullable&lt;&gt;) 替换为任何其他类型)。如果您查看GetUnderlyingType() 的来源(原始或反编译),您会发现它与我的代码非常相似。
【解决方案5】:

嗯,你可以使用:

return !(o is ValueType);

...但对象本身不可为空或其他 - type 是。您打算如何使用它?

【讨论】:

  • 这让我有点失望。例如诠释?我 = 5; typeof(i) 返回 System.Int32 而不是 Nullable -- typeof(int?) 返回 Nullable.. 我在哪里可以清楚地了解这个主题?
  • typeof(i) 将给出编译器错误-您不能将 typeof 与变量一起使用。你到底做了什么?
  • i.GetType() 将首先装箱到 Object,并且没有装箱的可为空类型之类的东西 - Nullable 装箱为空引用或装箱的 int。
  • 这样比 Nullable.GetUnderlyingType(type) != null ?
  • @Kiquenet:我们这里没有类型——只有值。
【解决方案6】:

我能想到的最简单的方法是:

public bool IsNullable(object obj)
{
    Type t = obj.GetType();
    return t.IsGenericType 
        && t.GetGenericTypeDefinition() == typeof(Nullable<>);
}

【讨论】:

  • +1。盒装可空类型的出色解决方案。我还没有专门测试过这个。因此,如果其他人可以验证,将不胜感激。
  • 我已经测试过了。我必须创建一种Nullable 类型,但具有不同的语义。在我的情况下,我应该支持 null 作为有效值,并且根本不支持任何值。所以创建了一个Optional 类型。由于有必要支持null 值,因此我还必须实现处理Nullable 值的代码作为我实现的一部分。这就是这段代码的来源。
  • 我认为这个解决方案是错误的。将 Nullable 值类型作为参数传递给期望对象类型参数的方法应该会导致装箱发生。 Nullable 是值类型,装箱转换的结果是引用类型。没有装箱的空值。我相信这个方法总是返回 false?
  • 任何关于它的测试就像另一个答案?
  • 由于装箱值,它不起作用。它总是返回 FALSE。
【解决方案7】:

这里有两个问题:1)测试一个Type是否可以为空; 2) 测试一个对象是否代表一个可为空的类型。

对于问题 1(测试类型),这是我在自己的系统中使用的解决方案:TypeIsNullable-check solution

对于问题 2(测试对象),Dean Chalk 的上述解决方案适用于值类型,但不适用于引用类型,因为使用 重载总是返回 false。由于引用类型本质上可以为空,因此测试引用类型应始终返回 true。有关这些语义的解释,请参阅下面的注释 [关于“可空性”]。因此,这是我对 Dean 方法的修改:

    public static bool IsObjectNullable<T>(T obj)
    {
        // If the parameter-Type is a reference type, or if the parameter is null, then the object is always nullable
        if (!typeof(T).IsValueType || obj == null)
            return true;

        // Since the object passed is a ValueType, and it is not null, it cannot be a nullable object
        return false; 
    }

    public static bool IsObjectNullable<T>(T? obj) where T : struct
    {
        // Always return true, since the object-type passed is guaranteed by the compiler to always be nullable
        return true;
    }

这是我对上述解决方案的客户端测试代码的修改:

    int a = 123;
    int? b = null;
    object c = new object();
    object d = null;
    int? e = 456;
    var f = (int?)789;
    string g = "something";

    bool isnullable = IsObjectNullable(a); // false 
    isnullable = IsObjectNullable(b); // true 
    isnullable = IsObjectNullable(c); // true 
    isnullable = IsObjectNullable(d); // true 
    isnullable = IsObjectNullable(e); // true 
    isnullable = IsObjectNullable(f); // true 
    isnullable = IsObjectNullable(g); // true

我在 IsObjectNullable(T t) 中修改 Dean 的方法的原因是他的原始方法对于引用类型总是返回 false。由于像 IsObjectNullable 这样的方法应该能够处理引用类型的值,并且由于所有引用类型本质上都是可以为空的,因此如果传递了引用类型或 null,则该方法应该始终返回 true。

以上两种方法可以换成下面的单一方法,实现同样的输出:

    public static bool IsObjectNullable<T>(T obj)
    {
        Type argType = typeof(T);
        if (!argType.IsValueType || obj == null)
            return true;
        return argType.IsGenericType && argType.GetGenericTypeDefinition() == typeof(Nullable<>);
    }

但是,最后一种单一方法方法的问题在于,使用 Nullable 参数时性能会受到影响。当在 IsObjectNullable 调用中使用 Nullable 类型参数时,执行此单个方法的最后一行所需的处理器时间比允许编译器选择前面显示的第二个方法重载所需的处理器时间要多得多。因此,最佳解决方案是使用此处说明的两种方法。

CAVEAT:此方法只有在使用原始对象引用或精确副本调用时才能可靠地工作,如示例中所示。但是,如果一个可为空的对象被装箱到另一个类型(例如对象等)而不是保持其原始的 Nullable 形式,则此方法将无法可靠地工作。如果调用此方法的代码未使用原始的、未装箱的对象引用或精确副本,则无法使用此方法可靠地确定对象的可空性。

在大多数编码场景中,要确定可空性必须依赖于测试原始对象的类型,而不是其引用(例如,代码必须有权访问对象的原始类型才能确定可空性)。在这些更常见的情况下,IsTypeNullable(参见链接)是确定可空性的可靠方法。

附: - 关于“可空性”

我应该重复我在另一篇文章中关于可空性的声明,该声明直接适用于正确解决该主题。也就是说,我认为这里讨论的重点不应该是如何检查一个对象是否是一个泛型的 Nullable 类型,而是是否可以将 null 值赋给该类型的对象。换句话说,我认为我们应该确定一个对象类型是否可以为空,而不是它是否可以为空。区别在于语义,即确定可空性的实际原因,这通常是最重要的。

在使用对象的类型在运行时可能未知的系统中(Web 服务、远程调用、数据库、提要等),一个常见的要求是确定是否可以将空值分配给对象,或者是否对象可能包含一个空值。对不可为空的类型执行此类操作可能会产生错误,通常是异常,这在性能和编码要求方面都非常昂贵。为了采取主动避免此类问题的首选方法,有必要确定任意类型的对象是否能够包含空值;即,它是否通常是“可空的”。

在非常实际和典型的意义上,.NET 术语中的可空性并不一定意味着对象的类型是可空的形式。事实上,在很多情况下,对象都有引用类型,可以包含空值,因此都是可以为空的;这些都没有 Nullable 类型。因此,在大多数情况下,出于实际目的,应针对可空性的一般概念进行测试,而不是可空性的依赖于实现的概念。因此,我们不应该仅仅关注 .NET Nullable 类型而束手无策,而是在关注可空性的一般实用概念的过程中融入我们对其要求和行为的理解。

【讨论】:

    【解决方案8】:

    我想出的最简单的解决方案是实现微软的解决方案(How to: Identify a Nullable Type (C# Programming Guide))作为扩展方法:

    public static bool IsNullable(this Type type)
    {
        return Nullable.GetUnderlyingType(type) != null;
    }
    

    然后可以这样调用:

    bool isNullable = typeof(int).IsNullable();
    

    这似乎也是访问IsNullable() 的一种合乎逻辑的方式,因为它适合Type 类的所有其他IsXxxx() 方法。

    【讨论】:

    • 你不想用“==”代替“!=”吗?
    • 好点@vkelman 我没有做出改变,而是更新了答案以使用微软当前的建议,因为自从我写这篇文章以来,这已经改变了。
    【解决方案9】:

    在装箱可空类型(例如Nullable&lt;int&gt; 或 int?)时要小心:

    int? nullValue = null;
    object boxedNullValue = (object)nullValue;
    Debug.Assert(boxedNullValue == null);
    
    int? value = 10;
    object boxedValue = (object)value;
    Debug.Assert( boxedValue.GetType() == typeof(int))
    

    它变成了一个真正的引用类型,所以你失去了它可以为空的事实。

    【讨论】:

      【解决方案10】:

      也许有点离题,但仍然有一些有趣的信息。如果类型可以为空,我发现很多人使用Nullable.GetUnderlyingType() != null 来标识。这显然有效,但微软建议以下type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;)(请参阅http://msdn.microsoft.com/en-us/library/ms366789.aspx)。

      我从性能的角度来看这个。下面的测试(一百万次尝试)的结论是,当一个类型可以为空时,Microsoft 选项提供了最佳性能。

      Nullable.GetUnderlyingType(): 1335ms(慢 3 倍)

      GetGenericTypeDefinition() == typeof(Nullable): 500ms

      我知道我们谈论的是一小段时间,但每个人都喜欢调整毫秒 :-)!因此,如果您的老板希望您减少几毫秒,那么这就是您的救星……

      /// <summary>Method for testing the performance of several options to determine if a type is     nullable</summary>
      [TestMethod]
      public void IdentityNullablePerformanceTest()
      {
          int attempts = 1000000;
      
          Type nullableType = typeof(Nullable<int>);
      
          Stopwatch stopwatch = new Stopwatch();
          stopwatch.Start();
          for (int attemptIndex = 0; attemptIndex < attempts; attemptIndex++)
          {
              Assert.IsTrue(Nullable.GetUnderlyingType(nullableType) != null, "Expected to be a nullable"); 
          }
      
          Console.WriteLine("Nullable.GetUnderlyingType(): {0} ms", stopwatch.ElapsedMilliseconds);
      
          stopwatch.Restart();
      
          for (int attemptIndex = 0; attemptIndex < attempts; attemptIndex++)
         {
             Assert.IsTrue(nullableType.IsGenericType && nullableType.GetGenericTypeDefinition() == typeof(Nullable<>), "Expected to be a nullable");
         }
      
         Console.WriteLine("GetGenericTypeDefinition() == typeof(Nullable<>): {0} ms", stopwatch.ElapsedMilliseconds);
         stopwatch.Stop();
      }
      

      【讨论】:

      • 您好,测量时间可能存在一个问题,断言会影响结果。您是否在没有 Assert 的情况下进行了测试? Console.WriteLine 也应该在计量区域之外。 +1 尝试量化性能问题:)。
      • @ipavlu Console.WriteLine 确实在计量区域之外 ;)
      • Roel,正如 ipavlu 所提到的,Assert 应该在循环之外。其次,您还应该针对不可为空的对象对其进行测试,以测试是否存在错误情况。我进行了类似的测试(2 个可空对象和 4 个不可空对象),GetUnderlyingType 得到约 2 秒,GetGenericTypeDefinition 得到约 1 秒,即GetGenericTypeDefinition 快两倍(不是三次)。
      • 用 2 个可空值和 2 个不可空值再进行一轮 - 这次 GetUnderlyingType 慢了 2.5 倍。只有不可为空的 - 这次两者都是并驾齐驱。
      • 但更重要的是,GetUnderlyingType 在您必须检查可空性并获取底层类型(如果它是可空的)时很有用。这非常有用,您经常会看到类似Activator.CreateInstance(Nullable.GetUnderlyingType(type) ?? type) 的模式。就像as 关键字一样,检查演员阵容并返回结果。如果您想获得可空的底层类型,那么执行GetGenericTypeDefinition 检查然后获得泛型类型将是一个坏主意。 GetUnderlyingType 也更具可读性和难忘性。如果我只做大约 1000 次,我不会介意。
      【解决方案11】:

      我认为使用微软建议的针对IsGenericType 进行测试的那些很好,但是在GetUnderlyingType 的代码中,微软使用了一个额外的测试来确保你没有通过泛型类型定义Nullable&lt;&gt;:

       public static bool IsNullableType(this Type nullableType) =>
          // instantiated generic type only                
          nullableType.IsGenericType &&
          !nullableType.IsGenericTypeDefinition &&
          Object.ReferenceEquals(nullableType.GetGenericTypeDefinition(), typeof(Nullable<>));
      

      【讨论】:

        【解决方案12】:

        这个版本:

        • 缓存结果更快,
        • 不需要不必要的变量,例如 Method(T obj)
        • 并不复杂 :),
        • 只是静态泛型类,具有一次性计算字段

        public static class IsNullable<T>
        {
            private static readonly Type type = typeof(T);
            private static readonly bool is_nullable = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
            public static bool Result { get { return is_nullable; } }
        }
        
        bool is_nullable = IsNullable<int?>.Result;
        

        【讨论】:

        • 我认为您用静态声明“is_nullable”回答了自己。提示:用 int? 声明对象? (object a = (int?)8;) 看看会发生什么。
        【解决方案13】:

        这是我的想法,因为其他一切似乎都失败了 - 至少在 PLC - 可移植类库 / .NET Core 上使用 >= C# 6

        解决方案: 为任何类型 TNullable&lt;T&gt; 扩展静态方法,并使用与底层类型匹配的静态扩展方法将被调用并优先于泛型的事实T 扩展方法。

        对于T

        public static partial class ObjectExtension
        {
            public static bool IsNullable<T>(this T self)
            {
                return false;
            }
        }
        

        对于Nullable&lt;T&gt;

        public static partial class NullableExtension
        {
            public static bool IsNullable<T>(this Nullable<T> self) where T : struct
            {
                return true;
            }
        }
        

        使用反射和type.IsGenericType... 在我当前的 .NET 运行时集上不起作用。 MSDN Documentation 也没有帮助。

        if (type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;)) {…}

        部分原因是 .NET Core 中的反射 API 发生了相当大的变化。

        【讨论】:

          【解决方案14】:

          一个简单的方法:

              public static bool IsNullable(this Type type)
              {
                  if (type.IsValueType) return Activator.CreateInstance(type) == null;
          
                  return true;
              }
          

          这些是我的单元测试,都通过了

              IsNullable_String_ShouldReturn_True
              IsNullable_Boolean_ShouldReturn_False
              IsNullable_Enum_ShouldReturn_Fasle
              IsNullable_Nullable_ShouldReturn_True
              IsNullable_Class_ShouldReturn_True
              IsNullable_Decimal_ShouldReturn_False
              IsNullable_Byte_ShouldReturn_False
              IsNullable_KeyValuePair_ShouldReturn_False
          

          实际的单元测试

              [TestMethod]
              public void IsNullable_String_ShouldReturn_True()
              {
                  var typ = typeof(string);
                  var result = typ.IsNullable();
                  Assert.IsTrue(result);
              }
          
              [TestMethod]
              public void IsNullable_Boolean_ShouldReturn_False()
              {
                  var typ = typeof(bool);
                  var result = typ.IsNullable();
                  Assert.IsFalse(result);
              }
          
              [TestMethod]
              public void IsNullable_Enum_ShouldReturn_Fasle()
              {
                  var typ = typeof(System.GenericUriParserOptions);
                  var result = typ.IsNullable();
                  Assert.IsFalse(result);
              }
          
              [TestMethod]
              public void IsNullable_Nullable_ShouldReturn_True()
              {
                  var typ = typeof(Nullable<bool>);
                  var result = typ.IsNullable();
                  Assert.IsTrue(result);
              }
          
              [TestMethod]
              public void IsNullable_Class_ShouldReturn_True()
              {
                  var typ = typeof(TestPerson);
                  var result = typ.IsNullable();
                  Assert.IsTrue(result);
              }
          
              [TestMethod]
              public void IsNullable_Decimal_ShouldReturn_False()
              {
                  var typ = typeof(decimal);
                  var result = typ.IsNullable();
                  Assert.IsFalse(result);
              }
          
              [TestMethod]
              public void IsNullable_Byte_ShouldReturn_False()
              {
                  var typ = typeof(byte);
                  var result = typ.IsNullable();
                  Assert.IsFalse(result);
              }
          
              [TestMethod]
              public void IsNullable_KeyValuePair_ShouldReturn_False()
              {
                  var typ = typeof(KeyValuePair<string, string>);
                  var result = typ.IsNullable();
                  Assert.IsFalse(result);
              }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-10-11
            • 1970-01-01
            • 2019-06-09
            • 2013-02-13
            • 1970-01-01
            • 1970-01-01
            • 2010-09-17
            相关资源
            最近更新 更多