System.String是否可为空?

问题描述 投票:-1回答:1

[当我尝试使用csc(版本= 3.3.1-beta3-19461-02)编译以下简单C#源文件时,我收到一条错误消息,指出System.Stringnon-nullable类型:

using System;
#nullable enable

class Prg {

   static void Main() {
   //
   // Compiler says:
   //    error CS0453: The type 'string' must be a non-nullable value
   //    type in order to use it as parameter 'T'
   //    in the generic type or method 'Nullable<T>'
   //    
      Nullable<String> str = "xyz";

      Console.WriteLine(str);
   }
}

但是,我可以将System.String的实例设置为null值:

using System;

class Prg {

   static void Main() {
      String str = null;
      Console.WriteLine(str);
   }
}

我很困惑,因为System.String显然可以为空,但在第一个源代码片段中引起了矛盾的错误消息。

c# .net string nullable
1个回答
0
投票

我不知道矛盾在哪里?类型T必须是不可为空的,才能用作:

 Nullable<T> 

而且您不能使用Nullable<String>,因为字符串是nullable

© www.soinside.com 2019 - 2024. All rights reserved.