返回首页

为什么我们使用的是"使用"在类或函数的关键字,而"使用"关键字使用之前声明一个类。

像这样的


using System;

using System.IO;

using System.Text;

 

class MemStream

{

    static void Main()

    {

        int count;

        byte[] byteArray;

        char[] charArray;

        UnicodeEncoding uniEncoding = new UnicodeEncoding();

 

        // Create the data to write to the stream.

        byte[] firstString = uniEncoding.GetBytes(

            "Invalid file path characters are: ");

        byte[] secondString = uniEncoding.GetBytes(

            Path.GetInvalidPathChars());

 

        using(MemoryStream memStream = new MemoryStream(100))

        {

            // Write the first string to the stream.

            memStream.Write(firstString, 0 , firstString.Length);

 

            // Write the second string to the stream, byte by byte.

            count = 0;

            while(count < secondString.Length)

            {

                memStream.WriteByte(secondString[count++]);

            }

 

            // Write the stream properties to the console.

            Console.WriteLine(

                "Capacity = {0}, Length = {1}, Position = {2}\n",

                memStream.Capacity.ToString(),

                memStream.Length.ToString(),

                memStream.Position.ToString());

 

            // Set the position to the beginning of the stream.

            memStream.Seek(0, SeekOrigin.Begin);

 

            // Read the first 20 bytes from the stream.

            byteArray = new byte[memStream.Length];

            count = memStream.Read(byteArray, 0, 20);

 

            // Read the remaining bytes, byte by byte.

            while(count < memStream.Length)

            {

                byteArray[count++] =

                    Convert.ToByte(memStream.ReadByte());

            }

 

            // Decode the byte array into a char array

            // and write it to the console.

            charArray = new char[uniEncoding.GetCharCount(

                byteArray, 0, count)];

            uniEncoding.GetDecoder().GetChars(

                byteArray, 0, count, charArray, 0);

            Console.WriteLine(charArray);

        }

    }

}

 



该网站转介
]

回答

评论会员:SAKryukov 时间:2012/02/05
一个"用"与另一个"使用"无关。他们没有任何共同之处;这仅仅是关键字的经济
首先"使用"提供别名,并没有任何携带功能。没有一个单一的"使用"所有条款,您可以工作,但那么你就会有完全合格的所有名称。

第二种情况是使用声明。这是一个语法糖,自动呼叫System.IDisposable.Dispose的。实际上,你应该总是使用它时,你需要创建一个实现此接口的类的对象。它要求自动System.IDisposable.Dispose上即使抛出一个异常退出块。此功能是严格相当于实例化和处置使用try-finally块。
看到{A}]。顺便说一下,读的语言和平台的使用说明书,并密切关注细节。如果你做到了,你会节省很多时间。这个问题就没有必要

mdash;水杨酸
评论会员:苏雷什Suthar 时间:2012/02/05
在C#中使用关键字有两个主要用途:

 60;使用指令:创建其他命名空间中定义的命名空间或进口类型的别名。例如在你的上面的代码示例
{C} 声明:定义在年底将出售对象的范围。即

 using(MemoryStream memStream = new MemoryStream(100))

为更多细节使用语句{A2}]
在这里使用的指令{A3}]。

一} {A4纸的好文章]:manoharank5 | |当我们使用使用关键字时,它会调用这个类的方法执行后使用块内部处置

{A5的}]