I'm using the following right now:
foreach (string file in files) {
switch (filetype.Value) {
case "ReadFile":
ReadFile(file);
break;
case "ReadMSOfficeWordFile":
ReadMSOfficeWordFile(file);
break;
case "ReadMSOfficeExcelFile":
ReadMSOfficeExcelFile(file);
break;
case "ReadPDFFile":
ReadPDFFile(file);
break;
}
}
It works, but it feels kinda wrong. The Python way would be something more like this:
foreach string file in files:
filetype.Value(file)
I have a really hard time imagining that C# can't do something like this. It may be that my Google skills are bad, but I can't seem to figure it out.
SOLUTION
public static readonly IDictionary<string, Action<string>> FileTypesDict = new Dictionary<string,Action<string>> {
{"*.txt", ReadFile},
{"*.doc", ReadMSOfficeWordFile},
{"*.docx", ReadMSOfficeWordFile},
{"*.xls", ReadMSOfficeExcelFile},
{"*.xlsx", ReadMSOfficeExcelFile},
{"*.pdf", ReadPDFFile},
};
foreach (KeyValuePair<string, Action<string>> filetype in FileTypesDict) {
string[] files = Directory.GetFiles(FilePath, filetype.Key, SearchOption.AllDirectories);
//System.Reflection.MethodInfo ReadFileMethod = ReadFile.GetType().GetMethod(filetype.Value);
foreach (string file in files) {
FileTypesDict[filetype.Key](file);
}
}
Variables and functions have separate name spaces, which means a variable and a function can have the same name, such as value and value(), and Mata will not confuse them.
You cant because if you have example(), 'example' is a pointer to that function. This is the right answer. There are function pointers, which are variables. But also, all function names are treated as const function pointers!
Variables and functions share the same namespace in JavaScript, so they override each other. if function name and variable name are same then JS Engine ignores the variable. With var a you create a new variable. The declaration is actually hoisted to the start of the current scope (before the function definition).
Use getattr() to Assign a Function Into a Variable in Python The function getattr() returns a value of an attribute from an object or module. This function has two required arguments, the first argument is the name of the object or module, and the second is a string value that contains the name of the attribute.
You can do it with some preparation using delegates, like this:
private static readonly IDictionary<string,Action<string>> actionByType =
new Dictionary<string,Action<string>> {
{"ReadFile", ReadFile}
, {"ReadMSOfficeWordFile", ReadMSOfficeWordFile}
, {"ReadMSOfficeExcelFile", ReadMSOfficeExcelFile}
, {"ReadPDFFile", ReadPDFFile}
};
When it is time to call your action, do it as follows:
actionByType[actionName](file);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With