简体   繁体   中英

Pass static method stored in string in c#

How can I pass the static method with params which are stored in a string? I want to use method from another class with params. I have a dictionary depending on what folder which function should be used.
Here is main class:

foreach (string folder in folders)
  {
    foreach (string file in Directory.EnumerateFiles(folder))
     {
        //switch (folder)
        //{
        //}
      foreach(var a in GetDictionaryToFunction())
      {
       string nameFolder = folder.Split('\\')[folder.Split('\\').Count() - 1];
       if (a.Key == nameFolder)
        {
        //And here I want to use the specified method with file path as param.
          Type thisType = this.GetType();
          MethodInfo theMethod = thisType.GetMethod(a.Value);// +"("+ file + ")");
          theMethod.Invoke(theMethod, null);
         }
       }
  }

And I'm trying to use function from this class:

class File
{
    public static void ReadPayments(string filePath)
    {
        string[] rows = Reader.ReadCsv(filePath);
        if (rows.Count() == 0) return;

        listPlatnosci.Clear();
        string fileName = Path.GetFileName(filePath);

        foreach (string row in rows)
        {
            TransformRow(row, fileName);
        }
    }

example dictionary: <folder, FunctionToAddValues>

ReadPayments should be define as follow:

public class ClassWithTheMethod
{
    public static void ReadPayments(string folder)
    {
        //Whatever
    }
}

And call it by using this:

MethodInfo theMethod = typeof(ClassWithTheMethod).GetMethod(a.Value, BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string) }, null);
theMethod.Invoke(null, new object[] { a.Key }); //null for static methods

Here is code which worked for me:

MethodInfo theMethod = typeof(File).GetMethod(a.Value, BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string) }, null);
                            theMethod.Invoke(null, new object[] { file }); 

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