将 class 中的属性列表与字符串列表匹配

Match a list of properties in a class with a list of strings

我有这个对象:

 public partial class Subjects
{
    public Guid SubjectId { get; set; }
    public string Code { get; set; }
    public Guid OrganizationId { get; set; }
    public string PreferredName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public string Gender { get; set; }
    public string LastNameInitial { get; set; }
    public string CodeDisplay { get; set; }
    public Guid? RaceId { get; set; }
    public Guid? MaritalStatusId { get; set; }
    public Guid? StatusId { get; set; }
    public string Rank { get; set; }
    public string Email { get; set; }
    public string MobilePhone { get; set; }
    public bool MobilePhoneDoNotLeaveMsg { get; set; }
    public bool MobilePhoneDoNotText { get; set; }
    public string WorkPhone { get; set; }
    public bool WorkPhoneDoNotLeaveMsg { get; set; }
}

我有这个字符串列表,这些字符串是我需要加密的 class 中的属性名称:

public static List<string> EncryptedColumns = new List<string> { "SocialSecurityNumber", "CodeDisplay", "FirstName", "LastName", "MiddleName", "PreferredName", "LastNameInitial" };

现在这两个字符串匹配的方式是使用反射将列表中的每个项目检查为 class 中的 属性。如果匹配,则该值被加密。由于开销,我想避免为此使用反射。以下是当前程序如何进行匹配:

            foreach (string name in EncryptedColumns)
            {
                var property = encryptSubject.GetType().GetProperty(name);
                if (property != null)
                {
                    var value = property.GetValue(encryptSubject , null);
                    if (value != null)
                    {
                        string finalvalue = value.ToString();
                        
                        property.SetValue(encryptSubject, Encrypt(finalvalue), null);
                    }
                }
            }

这确实有效,但反射会带来很多开销。有更好的方法吗?

我认为既然您已经知道要加密什么,那么您可以在 getters/setters 中处理它。这就是它们在那里的原因,以封装如何设置值。

如果您希望此值只写:

    private string firstName;
    public string FirstName { get {return Encrypt(firstName);} set; }

或加密存储

    private string firstName;
    public string FirstName { get { return firstName} set {firstName = Encrypt(value)} }

动态查找要加密的属性,需要反射。这是获取 class.

成员名称的唯一方法

您也可以使用内置系统来处理这些类型的事情并添加自定义 Attribute

[MustEncryptCustom]
public string FirstName {get; set;}

并按照描述访问它们 here