惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
人人都是产品经理
人人都是产品经理
aimingoo的专栏
aimingoo的专栏
M
MIT News - Artificial intelligence
Recent Announcements
Recent Announcements
V
Visual Studio Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
MyScale Blog
MyScale Blog
Hugging Face - Blog
Hugging Face - Blog
宝玉的分享
宝玉的分享
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 叶小钗
博客园 - 聂微东
U
Unit 42
F
Fortinet All Blogs
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
IT之家
IT之家
The GitHub Blog
The GitHub Blog
Stack Overflow Blog
Stack Overflow Blog
MongoDB | Blog
MongoDB | Blog
Y
Y Combinator Blog
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)

博客园 - yfcomeon

浅谈C#托管程序中的资源释放问题 (转载) 静态构造函数的执行时机 详解javascript类继承机制的原理 通用高效分页存储过程 Attributes in C# 组装机 散列基本概念知识点 C#的6种常用集合类大比拼 C#中的集合类 C#中的集合类 C#里的委托和事件实现 C#方法修饰符 C#类和接口及值类型和引用类型的区别 vc调试器 SQL数据库空间不足怎么办 分页 B树算法 转:sql server系统表详细说明 转:sql server系统表详细说明
变量的域
yfcomeon · 2007-10-25 · via 博客园 - yfcomeon

比较这两段代码:
代码一:

1int i;
2            string text;
3            for(i=0;i<10;i++)
4            {
5                text = "Line" + Convert.ToString(i);
6                Console.WriteLine("{0}", text);
7            }

8            Console.WriteLine("Last text output in loop:{0}", text);
9            Console.ReadKey();

代码二:

1int i;
2            string text="";
3            for(i=0;i<10;i++)
4            {
5                text = "Line" + Convert.ToString(i);
6                Console.WriteLine("{0}", text);
7            }

8            Console.WriteLine("Last text output in loop:{0}", text);
9            Console.ReadKey();

代码一错误编译不了:提示--错误 1 使用了未赋值的局部变量“text” 
而代码二可以编译通过。
原因:主要涉及到分配给text变量的内存空间,实际上任何变量都是这样。只声明一个简单的变量类型,并不会引起其他的变化。
只有在给变量赋值后,这个字才占用一块内存空间。如果这种占据内存空间的行为在循环中发生,该值实际上定义为一个局部值,在循环的外部会超出其作用域。