Use variable in place of function name

后端 未结 6 1586
自闭症患者
自闭症患者 2021-02-09 13:16

I\'m using the following right now:

foreach (string file in files) {
    switch (filetype.Value) {
        case \"ReadFile\":
            ReadFile(file);
                


        
6条回答
  •  悲哀的现实
    2021-02-09 13:27

    If you're looking for a way to avoid the explicit mapping of method names to string values you could use reflection to do dynamic method invocation (this assumes filetype.Value is of type String)

    String method_name = String.Empty;
    foreach (string file in files) {
        method_name = filetype.Value;
        System.Reflection.MethodInfo method = this.GetType().GetMethod(method_name);
        method.Invoke(this, new object[]{file});
    }
    

提交回复
热议问题