【问题标题】:string alias works without System.String But String does not字符串别名在没有 System.String 的情况下工作,但 String 没有
【发布时间】:2012-10-20 10:01:46
【问题描述】:

我今天遇到了一个奇怪的困惑。虽然我在这篇文章中读到了 C# 中字符串和字符串之间的区别:What is the difference between String and string in C#?。但是当我尝试使用String 和大写字母而不使用命名空间System 时,它无法识别。喜欢

此代码有效,

using System;

String s = "";

但不使用System,会报错。

而带有小写字母的string 可以使用和不使用System 命名空间。

如果 String 和 string 是相同的东西,那么为什么一个只适用于它的命名空间,而其他的也适用于有和没有命名空间。

【问题讨论】:

  • 您是否确保 Using System; 命名空间包含在您的类文件中?正如您在提供的链接中看到的那样,string 是 System.String 的别名,因此它的行为符合预期。
  • 当包含使用系统时,字符串和字符串都可以工作。但是如果不包含它,则只有带有小写字母的字符串有效。如果两者都相同,那么为什么一个有效而另一个无效?
  • Usman,如果您读到article 接受的答案中的第一行是“字符串是 System.String 的别名”。这意味着如果你写小写字母 string 它将与 System.String 相同

标签: c# asp.net .net string


【解决方案1】:

string 是一个 C# 构造,在编译过程中翻译System.String

每个 C# 程序默认都有:

using string = System.String;
using char = System.Char;
using int = System.Int32;
using double = System.Double;

System.String 是类。如果无法访问 System 命名空间(因此,完全限定为 System.String 或使用 using System; 指令),您将无法使用类型 String

【讨论】:

    【解决方案2】:

    StringSystem.String 的别名。请参阅您链接到的 SO 答案中得分为 728 的答案,以获取一些别名的列表。如果您使用别名,它会自动获取 System. 位,因此您无需显式引用它,因为它已经存在。

    【讨论】:

      【解决方案3】:

      下面这样想

      假设我们有一个命名空间 Foo,它有一个名为 Boo 的类。现在,如果我们需要调用 Boo,我们需要使用“Using”关键字将其包含在项目中。

      如果我们为 ex 创建一个别名(不确定是否可能):Foo.Boo > NewBoo

      在这种情况下,编译器会将其视为 Foo.Boo

      这里是字符串大小写。

      当我们编写编译为 System.String 的 string 时,因此我们不需要对系统命名空间进行任何形式的包含来访问字符串。

      但如果是 Just String,我们需要包含它。

      【讨论】:

        【解决方案4】:

        确实如此,如果没有using System;,这将无法编译String name = "me"; 行中有一个波浪线

        class Program
        {
        
            static void Main(string[] args)
            {
                string name1 = "me";
        
                String name2 = "me";
            }
        
        }
        

        当我将鼠标放在string 上时,它显示class System.String,当我将它放在String 上时,它显示the type or namespace String could not be found

        【讨论】:

          【解决方案5】:

          System.String 是 System 命名空间的一个类。 字符串直接引用它。

          当您键入字符串时,您可以访问 System.String 的所有方法(和构造函数等)。

          Nullable<T> 相同: 你可以写,例子

          int? myInt = 2;
          

          其实是一样的

          Nullable<int> myInt = 2;
          

          仅别名实用程序

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-03-14
            • 2018-01-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多