c# - 字符串为 Nullable 返回 false

标签 c# .net

为什么:

 string s = "";
 bool sCanBeNull = (s is Nullable);
 s = null;

sCanBeNull 等于 false?

我正在编写一个代码生成器,需要确保传递给它的每个类型都可以为 null,如果不是的话。

       //Get the underlying type:
       var type = field.FieldValueType;

        //Now make sure type is nullable:
        if (type.IsValueType) 
        {
            var nullableType = typeof (Nullable<>).MakeGenericType(type);
            return nullableType.FullName;
        }
        else
        {
            return type.FullName;
        }

我是否需要显式检查字符串,或者我是否遗漏了什么?

最佳答案

is 告诉您一个值是属于特定类型还是派生自该特定类型。

Nullable 是一个通用的 struct,它允许非可空值的可空版本。

string 不是 Nullable

要判断一个类型是否可以具有 null 值,请使用以下事实:对于所有此类类型,默认值为 null,而对于所有其他类型,则不是:

default(string) == null; // true

关于c# - 字符串为 Nullable 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32498732/

相关文章:

c# - 如何生成 appsettings.<EnvironmentName>.json 文件?

c# - F# for C#/Haskell 程序员

c# - 从资源文件中获取 DisplayName

c# - 如何在 C# 中解析 JsonObject

c# - win窗体中的数据表

c# - 生成datalist次数

c# - 如何在 .net 4 中异步执行 Action

.net - .Net 4.6 可以在 linux 上运行吗

.net - 测试 NetworkStream 是否关闭

c# - 在 setter 中获取属性名称