C# 如何检查对象是否可为空

标签 c#

<分区>

在stack overflow看到一个问答

How to check if an object is nullable?

我无法在上面发表评论,因为我没有超过 50 条评论,这就是我在这里提问的原因。

if(Nullable.GetUnderlyingType(myType) !=null)
{
   // It's Nullable
}

如果 myType 是 system.string

Nullable.GetUnderlyingType(myType) 

返回空值

我认为 System.string 可以为空!

最佳答案

来电Nullable.GetUnderlyingType()不会为 typeof(string) 返回任何有意义的信息. documentation提及:

Returns the underlying type argument of the specified nullable type.

Return Value

The type argument of the nullableType parameter, if the nullableType parameter is a closed generic nullable type; otherwise, null.

换句话说,如果您实际传递给它一个实现了 Nullable<T> 的类型,它只会返回有用的东西。 ,例如 int? , bool? , 等等。 就是这里“可空类型”的意思。

您还可以在 Marc's answer to the question you link to 的代码中看到它的预期用途:

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

关于C# 如何检查对象是否可为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41426279/

相关文章:

c# - 如何使用 C# 仅从多级嵌入式 MongoDB 文档获取具有相应父级的确切子元素

c# - asp.net 日历日期范围

c# - System.Text.Json 中的动态类型处理/"object"属性的自定义反序列化

c# - 在 WPF 中,在项目中使用 Struct 或 Class 作为具有 MVVM 模式的模型?

c# - [Azure 数据目录] : Read the data from Azure data catalog glossary Unauthorized error?

c# - 带有 ssl 的 asp.net 表单 - 拒绝访问日志文件

c# - 在 Entity Framework 6 中保存分离的实体

c# - 如何解决 C# 中的重复命名空间

c# - 如何将字符串数组中的值传递到 C# 中的正则表达式

c# - AutoMapper 后图