您的位置:首页 > 编程语言 > C#

我的c#之路(3.using语句)

2014-04-25 21:26 411 查看
using语句

1.

-有助于确保正确处理IDisposable对象(如文件和字体)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace c1
{
class Program
{
static void Main()
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(@"c:\test.txt"))
{
string s = null;
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
}

-可以将多个对象与using语句一起使用,但必须在using语句中声明这些对象

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace c1
{
class Program
{
static void Main()
{
using (Font font1 = new Font("Arial", 10.0f), font2 = new Font("Arial", 10.0f))
{
//Use font1 and font2
}
}
}
}

-可以实例化资源对象,然后将变量传递给using语句,但这不是最佳做法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace c1
{
class Program
{
static void Main()
{
Font font1 = new Font("Arial",10.0f);
using (font1)
{
//Use font1
}
//font1 is still in scope
//but the method call throws an exception
float f = font1.GetHeight();
}
}
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c#