我在旧项目中的类遇到问题,我不知道如何重构这部分,我从sonarcube收到以下错误消息:
Use an immutable collection or reduce the accessibility of the field(s) 'CreateContactMapping'.Why is this an issue?
这是一段代码
public static readonly Dictionary<string, Func<UpdateContactServiceRequest, object>> UpdateContactMapping =
new Dictionary<string, Func<UpdateContactServiceRequest, object>>
{
{ "firstname", req => req.FirstName },
{ "lastname", req => req.LastName },
{ "full_name", req => req.FullName },
{ "email", req => req.Email },
{ "phone", req => req.Phone },
{ "date_of_birth", req => req.BirthDate },
{ "job_title", req => req.JobTitle },
{ "occupation", req => req.Occupation },
{ "renda", req => req.MonthlyIncome },
{ "lifecyclestage", req => req.LifeCycleStage },
{ "hs_lead_status", req => req.LeadStatus },
{ "ali_email_validated", req => req.EmailValidated },
{ "ali_sms_token_validated", req => req.CellphoneValidated },
{ "id_da_proposta_atual", req => req.CurrentProposalId },
{ "contact_type", req => req.ContactType }
};
如何最好地解决这个问题?
一种解决方案是将
Dictionary
更改为 ImmutableDictionary
,然后在初始化字典后运行 .ToImmutableDictionary()
。
public static readonly ImmutableDictionary<string, Func<UpdateContactServiceRequest, object>> UpdateContactMapping = new Dictionary<string, Func<UpdateContactServiceRequest, object>>
{
{ "firstname", req => req.FirstName },
{ "lastname", req => req.LastName },
{ "full_name", req => req.FullName },
{ "email", req => req.Email },
{ "phone", req => req.Phone },
{ "date_of_birth", req => req.BirthDate },
{ "job_title", req => req.JobTitle },
{ "occupation", req => req.Occupation },
{ "renda", req => req.MonthlyIncome },
{ "lifecyclestage", req => req.LifeCycleStage },
{ "hs_lead_status", req => req.LeadStatus },
{ "ali_email_validated", req => req.EmailValidated },
{ "ali_sms_token_validated", req => req.CellphoneValidated },
{ "id_da_proposta_atual", req => req.CurrentProposalId },
{ "contact_type", req => req.ContactType }
}.ToImmutableDictionary();
使用不可变集合:您可以使用不可变集合(例如 ImmutableDictionary
public static readonly ImmutableDictionary<string, Func<UpdateContactServiceRequest, object>> UpdateContactMapping = ImmutableDictionary<string, Func<UpdateContactServiceRequest, object>>.Empty
.Add("firstname", req => req.FirstName)
.Add("lastname", req => req.LastName)
.Add("full_name", req => req.FullName)
// Add the rest of the key-value pairs
;
减少可访问性:如果您想继续使用Dictionary
private static readonly Dictionary<string, Func<UpdateContactServiceRequest, object>> UpdateContactMapping = new Dictionary<string, Func<UpdateContactServiceRequest, object>>
{
{ "firstname", req => req.FirstName },
{ "lastname", req => req.LastName },
// Add the rest of the key-value pairs
};
public static IReadOnlyDictionary<string, Func<UpdateContactServiceRequest, object>> GetUpdateContactMapping()
{
return UpdateContactMapping;
}