代码1
static void Main(string[] args)
{
string s1 = "Hello1";
{
TestClass tc = new TestClass();
}
string s2 = "Hello2";
Console.ReadKey();
}代码2
static void Main(string[] args)
{
string s1 = "Hello1";
TestClass tc = new TestClass();
string s2 = "Hello2";
Console.ReadKey();
}看到有人这么写,我自己尝试了下,并查看IL,在C#代码中似乎只有限制变量的“使用范围”,在IL 也只是多了一个NOP 指令。
那么,这样书写,有什么意义?
我一开始以为是 【摧毁】 tc 这个变量。可是并没有。由于有了这样的疑问。假设花括号并没有摧毁变量,那么:int x;
if(bool)
{
x = 10;
}和;
if(bool)
{
int x = 10;
}
似乎没区别?个人感觉前者作用更大,可以在接下来的代码,继续使用【x】这个变量,赋予新的作用。
static void Main(string[] args)
{
string s1 = "Hello1";
{
TestClass tc = new TestClass();
}
string s2 = "Hello2";
Console.ReadKey();
}代码2
static void Main(string[] args)
{
string s1 = "Hello1";
TestClass tc = new TestClass();
string s2 = "Hello2";
Console.ReadKey();
}看到有人这么写,我自己尝试了下,并查看IL,在C#代码中似乎只有限制变量的“使用范围”,在IL 也只是多了一个NOP 指令。
那么,这样书写,有什么意义?
我一开始以为是 【摧毁】 tc 这个变量。可是并没有。由于有了这样的疑问。假设花括号并没有摧毁变量,那么:int x;
if(bool)
{
x = 10;
}和;
if(bool)
{
int x = 10;
}
似乎没区别?个人感觉前者作用更大,可以在接下来的代码,继续使用【x】这个变量,赋予新的作用。
{
int x = 10;
}
这个应该在外边不能在使用x吧
if(bool)
{
int x = 10;
}
x=5
试下 猜的
TestClass tc = new TestClass();
只在范围内有效
}
{}在C# 中,表示层次关系、表示复合语句、表示数组元素。
{
//code..1
}else
{
//...2
}
//--------------------------------------------
if(a>b)
//code
//...2
{
int i = 0;
}
{
int i = 0;//没错
}
{
int i = 0;//没错
}
{
int i = 0;//没错
}
//最后还是会产生四个变量...那个i只是个给程序员看的标识,编译器不管它叫啥的...int i = 0;
int i = 0;//编译错误...A local variable named 'i' is already defined in this scope
int i = 0;//编译错误...A local variable named 'i' is already defined in this scope
int i = 0;//编译错误...A local variable named 'i' is already defined in this scope说实在的,直接这么用是没啥意义...
不过我想说的是,
这样的语法是否存在:可以[尽快]的摧毁对象?我回宿舍后,试试在花括号后强制调用GC,看看TestClass析构函数有没有被执行(原本是执行在 Main 函数执行完毕后)。
using()
{
}
using System;class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
} void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited resource.");
}
}class Program
{
static void Main()
{
using (C c = new C())
{
c.UseLimitedResource();
}
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}
{
public TestClass()
{
Console.WriteLine("I Coming...");
}
~TestClass()
{
Console.WriteLine("I Leaving...");
} #region IDisposable 成员 public void Dispose()
{
} #endregion
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main Start");
using (TestClass tc = new TestClass()) { }
Console.WriteLine("Main End");
Console.ReadKey();
}
}TO 10:
IDisposable 个人理解,应该只是【释放】,不是【摧毁】。
上面的示例,可以说明
强制调用gc,资源并不一定马上就被销毁,得等到gc下一次扫描
本人只在Debug模式生成下才看到过 应该与花括号无关
谢谢17楼指出这个错误 刚刚查了微软对这个指令的描述 no operation
但是有前辈将它翻译成 修补操作码 会不会是在这一步执行了栈帧寻址呢(个人猜想)
哪位大大知道 望不吝赐教