Use variable in place of function name

后端 未结 6 1576
自闭症患者
自闭症患者 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:24

    You can use a delegate:

    Action action;
    switch (filetype.Value) {
      case "ReadFile":
        action = ReadFile;
        break;
      case "ReadMSOfficeWordFile":
        action = ReadMSOfficeWordFile;
        break;
      case "ReadMSOfficeExcelFile":
        action = ReadMSOfficeExcelFile;
        break;
      case "ReadPDFFile":
        action = ReadPDFFile;
        break;
      default: 
        throw new NotImplementedException("Unhandled file type '"+filetype.Value+"'.");
    }
    foreach (string file in files) {
      action(file);
    }
    

提交回复
热议问题