从方法参数生成 DTO?



假设我有以下方法:

public async Task<IList<AnalysisResult>> GetAnalysis(short year, bool unPlanned = false,
Guid? departmentId = null, Guid? personnelId = null, CollarColor? collarColor = null,Guid? factoryId = null)
{
...
}

方法参数列表很长且难以管理。这是最轻的之一。

我想做的是将这些参数列表自动转换为 DTO 类。

例如:

如果我举例说明上述方法:

public class GetAnalysisPayload
{
public short Year {get;set;}
public bool UnPlanned {get;set;}
public Guid? DepartmentId {get;set;}
...
}

我使用了 ReSharper 的此功能,它是 JetRanins 的产品,但应用程序冻结并关闭,没有任何响应。虽然我重复了很多次,但我无法解决问题。还有人有想法吗?

这是我肮脏但有帮助的方法,主要是正则表达式的东西。

!答案正在进行中,只是不时保存以避免可怕的后退按钮

1:清洁:格式

确保声明都在每个函数的一行中,IMO 这将有助于解决这个问题。

输入:

public async Task<IList<AnalysisResult>> GetAnalysis(short year, bool unPlanned = false,
Guid? departmentId = null, Guid? personnelId = null, CollarColor? collarColor = null,Guid? factoryId = null)
{
...
}
public async Task<IList<AnalysisResult>> GetOtherStuff(string foo = "bar", bool foobar = false, Guid? factoryId = null)
{
...
}

正则表达式:,rn

替换为:,

输出:

public async Task<IList<AnalysisResult>> GetAnalysis(short year, bool unPlanned = false,     Guid? departmentId = null, Guid? personnelId = null, CollarColor? collarColor = null,Guid? factoryId = null)
{
...
}
public async Task<IList<AnalysisResult>> GetOtherStuff(string foo = "bar", bool foobar = false, Guid? factoryId = null)
{
...
}

2:更多清理:过滤和创建单个文件

为此,需要在专用文件夹中工作。

从上面的结果中获取输入文件。在下面的脚本中,它是"输入.cs">

让我们只选择以"公共"或"公共异步任务"开头的行,如果它们都是异步的。

创建类似filter.ps1的脚本

$regex = "^s*public async Task[^(]*s+([^(]+)" #capture the name of the function, i.e. the part before the opening parenthesis and space after Task<... type
get-content input.cs | % { if($_ -match $regex) {Set-Content -Path "$($matches[1])Payload.cs" -Value $_ } }

并在仅存在脚本和文件输入.cs的文件夹中执行它。

免责声明:在上面的代码中,我假设您在函数的返回类型中没有括号或空格!如果您有一些具有多个类型参数或元组的泛型方法,则可能会发生这种情况。

输出:2 个单独的文件,GetAnalysisPayload.cs个和GetOtherStuffPayload.cs每个文件只有函数声明行。

3:巧妙地分割每行

拆分(,,使用一些巧妙的格式,这将首先给出"DTO 类标头"和参数列表。

(正则表达式/PowerShell代码待给出(

根据您在此步骤中拥有的内容,这可能会变得混乱,但是如果函数像您的示例一样,它可以为您提供非常接近此步骤所需的近似值。

然后

有一些时间(几个小时?我会使用 Powershell 脚本或 C# 控制台应用程序对其进行润色,以节省部分"不可避免的"剩余手动工作。

例如,在每个文件顶部添加所需的"using"语句。

我引用的是"不可撤销",因为晚上有人告诉一些正则表达式向导只能用正则表达式来处理这项工作。

最新更新