C# 使用不可变集合或减少字段“CreateContactMapping”的可访问性

Posted

技术标签:

【中文标题】C# 使用不可变集合或减少字段“CreateContactMapping”的可访问性【英文标题】:C# Use an immutable collection or reduce the accessibility of the field(s) 'CreateContactMapping' 【发布时间】:2021-04-13 15:19:02 【问题描述】:

我在一个旧项目中遇到了一个类的问题,我不知道如何重构这部分,我从 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 
        ;

如何最好地解决这个问题?

【问题讨论】:

【参考方案1】:

一种解决方案是将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();

【讨论】:

解决了我的问题,非常感谢!

以上是关于C# 使用不可变集合或减少字段“CreateContactMapping”的可访问性的主要内容,如果未能解决你的问题,请参考以下文章

Java中如何快捷的创建不可变集合

Java中如何快捷的创建不可变集合

Java中如何快捷的创建不可变集合

Java中如何快捷的创建不可变集合

可变类型的安全性——更锋利的C#代码小记

Scala 集合中的可变与不可变