本文介绍了了解实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#编程的新手,并且对以下代码有疑问:

我看到通过FileInfo someFile = new FileInfo("c:\\test.txt");
创建了someFile的新实例
然后,代码检查文件是否存在,如果不存在,则创建该文件.但是,看起来它正在创建另一个实例: someFile = new FileInfo("c:\\test.txt");
在这一点上,是否已经存在一个实例?我们不是仅使用该实例来执行FileSteam someFileSteam = someFile.Create(); 语句吗?

完成后,还有另一个someFile = new FileInfo("c:\\test.txt");
这是因为textToAdd.Close(); 关闭了我们打开的某些文件的实例吗?

所以,我想我的问题是,为什么某些文件的某些实例被打开了三个(如果文件已经存在,则为两个)

I''m new to c# programming and have a question regarding the following code:

I see the a new instance of someFile is created via FileInfo someFile = new FileInfo("c:\\test.txt");

The code then checks if the file exists, if not, it creates it. But then it looks like it''s creating another instance : someFile = new FileInfo("c:\\test.txt");
At this point, isn''t there an instance already delcared? Didn''t we just use that instance to execute the FileSteam someFileSteam = someFile.Create(); statement?

Furhter done, there is yet another someFile = new FileInfo("c:\\test.txt");
Is this because textToAdd.Close(); closes out the instance of somefile that we had opened?

So, I guess my question is why some many instances of somefile being open three (two if the file exists already)

static void FileInfoClass()
        {
            // Create a file
            FileInfo someFile = new FileInfo("c:\\test.txt");
            if (!someFile.Exists)
            {
                FileStream someFileStream = someFile.Create();
                someFileStream.Close();
                someFile = new FileInfo("c:\\test.txt");
            }
            StreamWriter textToAdd;
            textToAdd = someFile.CreateText();
            textToAdd.WriteLine("This is a line in the file.");
            textToAdd.Flush();
            textToAdd.Close();
            textToAdd = someFile.AppendText();
            textToAdd.WriteLine("This is another line in the file.");
            textToAdd.Flush();
            textToAdd.Close();
            someFile = new FileInfo("c:\\test.txt");
            Console.WriteLine("File name: {0}", someFile.Name);
            Console.WriteLine("Full name: {0}", someFile.FullName);
            Console.WriteLine("Size: {0}", someFile.Length);
            Console.WriteLine();
            if (someFile.Exists)
            {
                someFile.CopyTo("c:\\test2.txt");
            }
            someFile.Delete();
        }

推荐答案


这篇关于了解实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 14:43