我可以从 c# 9 记录自动生成的方法中隐藏敏感的 属性 值吗?
Can I hide sensitive property values from a c# 9 record's autogenerated methods?
我正在构建一个用户管理系统,我要向其发送命令的域主机。这些命令是 record
,这既是因为 init
-only 属性,也是因为生成的辅助方法。但是,我很快 运行 遇到了这种方法的问题,例如LoginUserCommand
.
command.ToString()
returns 像这样(添加了格式):
LoginUserCommand {
Identity = 10000000-1111-2222-3333-444444444444,
CorrelationId = 20000000-1111-2222-3333-444444444444,
Timestamp = 2013-07-26T16:45:20Z,
IssuingUserId = 30000000-1111-2222-3333-444444444444,
EntityId = a80c081c-cf91-4304-9baa-20fb20c8d9f7,
IPAddress = 127.0.0.1,
Password = ThisIsAPr0blem
}
显然我可以解决这个问题,例如在重要的 类 上覆盖 ToString()
。天真地,我可能会做类似
的事情
public override string ToString()
{
return base.ToString()
.Replace(Password, "********");
}
但我想知道我是否忽略了一些内置方法让生成的 ToString()
方法掩盖 Password
属性.[=20= 的值]
您可以使用 with
语法重新映射您的记录并改用 PrintMembers
,我认为这样更简洁:
public override string ToString()
{
var builder = new StringBuilder();
(this with { Password = null }).PrintMembers(builder);
return builder.ToString();
}
还有proposals for introducing an attribute such as [PrintMembersIgnore]
for records, but nothing like it has been implemented. It can however be solved with code generation, which was the method suggested by the dotnet team (see comment in the thread), a project for this已经开始了
我正在构建一个用户管理系统,我要向其发送命令的域主机。这些命令是 record
,这既是因为 init
-only 属性,也是因为生成的辅助方法。但是,我很快 运行 遇到了这种方法的问题,例如LoginUserCommand
.
command.ToString()
returns 像这样(添加了格式):
LoginUserCommand {
Identity = 10000000-1111-2222-3333-444444444444,
CorrelationId = 20000000-1111-2222-3333-444444444444,
Timestamp = 2013-07-26T16:45:20Z,
IssuingUserId = 30000000-1111-2222-3333-444444444444,
EntityId = a80c081c-cf91-4304-9baa-20fb20c8d9f7,
IPAddress = 127.0.0.1,
Password = ThisIsAPr0blem
}
显然我可以解决这个问题,例如在重要的 类 上覆盖 ToString()
。天真地,我可能会做类似
public override string ToString()
{
return base.ToString()
.Replace(Password, "********");
}
但我想知道我是否忽略了一些内置方法让生成的 ToString()
方法掩盖 Password
属性.[=20= 的值]
您可以使用 with
语法重新映射您的记录并改用 PrintMembers
,我认为这样更简洁:
public override string ToString()
{
var builder = new StringBuilder();
(this with { Password = null }).PrintMembers(builder);
return builder.ToString();
}
还有proposals for introducing an attribute such as [PrintMembersIgnore]
for records, but nothing like it has been implemented. It can however be solved with code generation, which was the method suggested by the dotnet team (see comment in the thread), a project for this已经开始了