Avoiding repetitive code in multiple similar methods (C#)(避免在多个类似方法中重复代码 (C#))
问题描述
大家好!
我在 C# 中有一组(可能还有几十个)非常相似的方法.它们都建立在几乎相同的模式上:
I have a set of a few (and potentially will have dozens more) of very similar methods in C#. They all built on almost identical pattern:
ResultObjectType MethodX(...input parameters of various types...)
{
nesting preparation code here...
{
{
resultObject = ExternalClass.GetResultForMethodX(input parameters of MethodX);
}
}
nesting result processing code here ...
return resultObject;
}
重复/相同部分:ResultObjectType,准备代码,结果处理代码.
不同部分:要调用的外部类方法,输入参数集(输入参数的数量,它们的类型).
重要提示:我无法控制方法签名 - 无法更改它们.
我试图避免使用类似这样的代码重复所有类似代码块:
I am trying to avoid repeating all blocks of similar code with something like this:
ResultObjectType MethodX(...input parameters of various types...)
{
return UniversalMethod(
new ExternalMethodDelegate(ExternalClass.GetResultForMethodX),
input parameters of MethodX...);
}
ResultObjectType UniversalMethod (Delegate d, input parameters of various types...)
{
nesting preparation code...
{
{
resultObject =
(d as ExternalMethodDelegate)(same input parameters as above);
}
}
nesting result processing code...
return resultObject;
}
到目前为止,我只设法使其以这种方式工作,以防所有参数在编码时具有相同的已知类型.经过多次尝试用通用代表解决这个问题后,我开始认为这是不可能实现的.即使我的代码编译,它在运行时也不起作用.有接盘侠吗?提前感谢您的帮助!
So far I only managed to make it work in this manner in case where all parameters have the same known type at the time of coding. After a number of attempts to tackle this problem with generic delegates I am starting to think this is not possible to achieve. Even when my code compiles, it does not work at runtime. Any takers? Thanks in advance for your help!
推荐答案
下面是一个使用泛型委托的例子:
Here's an example using generic delegates:
int MethodY(int something, int other)
{
return UniversalMethod(() => GetResultForMethodY(something, other));
}
string MethodX(string something)
{
return UniversalMethod(() => GetResultForMethodX(something));
}
T UniversalMethod<T>(Func<T> fetcher)
{
T resultObject;
//nesting preparation code here...
{
resultObject = fetcher();
}
//nesting result processing code here ...
return resultObject;
}
如果 ResultObjectType 始终相同,则可以删除所有 T.
If ResultObjectType is always the same then you can remove all Ts.
这篇关于避免在多个类似方法中重复代码 (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:避免在多个类似方法中重复代码 (C#)
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
