Use variable in place of function name

后端 未结 6 1578
自闭症患者
自闭症患者 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-09 13:40

    You could keep a Dictionary of delegates, as the simplest way:

    Dictionary> fileReaders = new Dictionary>() {
        {"ReadFile", ReadFile},
        {"ReadOfficeWordFile", ReadOfficeWordFile},
        {"ReadOfficeExcelFile", ReadOfficeExcelFile},
        {"ReadPDFFile", ReadPDFFile}
    };
    

    Then call it like this:

    fileReaders[fileType.Value](file);
    

    Depending on what your methods return, you may have to change the type of the delegate (Action means void something(string someparam) as a method signature, for example) as well.

提交回复
热议问题