请问有关string 变量初始化的问题

oract666 2007-02-27 03:07:25
c# 编译器需要用某个初始值对变量进行初始化,之后才能在操作中引用该变量
但是这段代码:
using System;

namespace Wrox.ProCSharp.Basics
{
class MyFirstCSharpClass
{

static void Main()
{
string ttt;
ttt = Console.ReadLine();
Console.WriteLine(ttt);
Console.ReadLine();
return;
}
}
}

其中仅仅声明了string 引用ttt ,并没有用new初始化string对象
为何也能通过呢??
...全文
250 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
北京的雾霾天 2007-02-27
  • 打赏
  • 举报
回复
sorry!
我是说错了,string类型的默认是null,而不是"",只有值类型的才有默认的值,比如int默认为0.

我没有说错的是如果string没有用变量初始化也是有值的,不过值是null.
syeerzy 2007-02-27
  • 打赏
  • 举报
回复
int ttt;
Console.WriteLine(ttt);


编译通过或不通过取决于默认配置文件,在VS.NET中,C#默认不允许这么做,但是可以通过改变配置和使用编译特性使这种语句可以正常编译运行.
syeerzy 2007-02-27
  • 打赏
  • 举报
回复
一楼说:
如果没有初始化变量,则按如下默认:
string: ""或string.Empty

不是吧?????

string 是默认为null的.


"c# 编译器需要用某个初始值对变量进行初始化,之后才能在操作中引用该变量"

如果这么说,那后面的赋值语句 ttt = Console.ReadLine(); 就是可以看成对变量做的"初始化".


前面你说的"引用"该变量, 是指读操作. 对内存变量进行写操作并不一定要求这个变量已经初始化过.

Red_angelX 2007-02-27
  • 打赏
  • 举报
回复
ttt = Console.ReadLine();
这不就赋值了么 自动初始化
等价于
string tt;
tt="hello";
oract666 2007-02-27
  • 打赏
  • 举报
回复
如果没有初始化变量,则按如下默认:
string: ""或string.Empty
int:0
bool: false
...

是这样吗?
using System;

namespace Wrox.ProCSharp.Basics
{
class MyFirstCSharpClass
{

static void Main()
{
int ttt;
Console.WriteLine(ttt);
Console.ReadLine();
return;
}
}
}


就无法通过啊

using System;

namespace Wrox.ProCSharp.Basics
{
class MyFirstCSharpClass
{

static void Main()
{
int ttt=5;
Console.WriteLine(ttt);
Console.ReadLine();
return;
}
}
}

就可以
752 2007-02-27
  • 打赏
  • 举报
回复
你把“ttt = Console.ReadLine();”拿掉试试
csShooter 2007-02-27
  • 打赏
  • 举报
回复
string跟String不一样!前面需要编译器通过N次处理,优化!

所有建议使用string基本类型,而非String...(听说地)
北京的雾霾天 2007-02-27
  • 打赏
  • 举报
回复
如果没有初始化变量,则按如下默认:
string: ""或string.Empty
int:0
bool: false
...

110,559

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧