Home > Software engineering >  Pass static method stored in string in c#
Pass static method stored in string in c#

Time:12-21

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>

CodePudding user response:

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

CodePudding user response:

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 }); 
  • Related