简体   繁体   中英

How do I pass one method as a parameter to another method?

I have this code:

private void SearchForDoc()
        {
            try
            {
                outputtext = @"c:\temp\outputtxt";
                outputphotos = @"c:\temp\outputphotos";
                temptxt = @"c:\temp\txtfiles";
                tempphotos = @"c:\temp\photosfiles";
                if (!Directory.Exists(temptxt))
                {
                    Directory.CreateDirectory(temptxt);
                }
                if (!Directory.Exists(tempphotos))
                {
                    Directory.CreateDirectory(tempphotos);
                }
                if (!Directory.Exists(outputtext))
                {
                    Directory.CreateDirectory(outputtext);
                }
                if (!Directory.Exists(outputphotos))
                {
                    Directory.CreateDirectory(outputphotos);
                }
                t = Environment.GetEnvironmentVariable(Environment.GetFolderPath(Environment.SpecialFolder.Personal));

                ApplyAllFiles(t,ProcessFile(t);
                for (int i = 0; i < textfiles.Length; i++)
                {


                        FileInfo fi = new FileInfo((textfiles[i]));
                        DirectoryInfo d = new DirectoryInfo(temptxt);
                        long dirSize = DirSize(d);

                        if ((dirSize + fi.Length) <= 8388608)
                            fi.CopyTo(temptxt + "\\" + fi.Name, true);
                        else
                            break;

                }

Then in after this i have two methods:

static void ProcessFile(string path) {/* ... */}
        static void ApplyAllFiles(string folder, Action<string> fileAction)
        {
            foreach (string file in Directory.GetFiles(folder))
            {
                fileAction(file);
            }
            foreach (string subDir in Directory.GetDirectories(folder))
            {
                try
                {
                    ApplyAllFiles(subDir, fileAction);
                }
                catch
                {
                    // swallow, log, whatever
                }
            }
        }

Using this two methods in my method should get all text files from the document directory and all its subdirectories.

In my method i did:

ApplyAllFiles(t,ProcessFile(t);

But that is wrong way to use it. How can i use the methods ?

由于ProcessFile方法已经具有与Action<string>相同的签名,因此您只需指定方法名称即可:

ApplyAllFiles(t, ProcessFile);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM