如果只有中间线不同,我如何加入这两种方法?
public static WeekendElectricityReportResult CalculateWeekendElectricityReportResult(string dataFilPath)
{
string newFile = CopyFile(dataFilPath);
GetOperationClient().GetWeeklyEleReport(newFile);
RemoveNotUsedFiles(dataFilPath, newFile);
return ReadCalculations<WeekendElectricityReportResult>(newFile);
}
public static WeekendGasReportResult CalculateWeekendGasReportResult(string dataFilPath)
{
string newFile = CopyFile(dataFilPath);
GetOperationClient().GetWeeklyGasReport(newFile);
RemoveNotUsedFiles(dataFilPath, newFile);
return ReadCalculations<WeekendGasReportResult>(newFile);
}
如果我将它们加入到一个泛型方法中,如何区分使用GetWeeklyEleReport或GetWeeklyGasReport的中间方法?
答案 0 :(得分:1)
您将使用委托。由于您没有在中间函数中返回值,因此可以使用Action
对象:
public static WeekendReportResult CalculateWeekendReportResult(string dataFilPath, Action<string> del)
{
string newFile = CopyFile(dataFilPath);
del(newFile);
RemoveNotUsedFiles(dataFilPath, newFile);
return ReadCalculations<WeekendGasReportResult>(newFile);
}
然后你会这样称呼这个方法:
Action<string> del = delegate(string file) {
GetOperationClient().GetWeeklyEleReport(file);
};
var eleReport = CalculateWeekendReportResult(file, del);
Action<string> del2 = delegate(string file) {
GetOperationClient().GetWeeklyGasReport(file);
};
var gasReport = CalculateWeekendReportResult(file, del2);
答案 1 :(得分:1)
public static T CalculateReportResult<T>(string dataFilPath, Action<OperationClient, string> getAct, Func<string, T> readFunc)
{
string newFile = CopyFile(dataFilPath);
getAct(GetOperationClient(), newFile);
RemoveNotUsedFiles(dataFilPath, newFile);
return readFunc(newFile);
}
然后你可以这样做:
public static WeekendElectricityReportResult CalculateWeekendElectricityReportResult(string dataFilPath)
{
return CalculateWeekendElectricityReportResult(dataFilPath, (client, path) => { client.GetWeeklyEleReport(path); }, file => ReadCalculations<WeekendElectricityReportResult>(file));
}
答案 2 :(得分:1)
您可以使用模式Template Method
。在C#中,可以在没有继承的情况下实现,只需将委托传递给模板方法。
public static T CalculateWeekendReportsResult<T>(string dataFilPath, Action<string> action)
{
string newFile = CopyFile(dataFilPath);
action(newFile);
RemoveNotUsedFiles(dataFilPath, newFile);
return ReadCalculations<T>(newFile);
}
用法是:
var report = CalculateWeekendReportsResult<WeekendElectricityReportResult>
(filePath, GetOperationClient().GetWeeklyEleReport);
或
var report = CalculateWeekendReportsResult<WeekendGasReportResult>
(filePath, GetOperationClient().GetWeeklyGasReport);