繁体   English   中英

C#属性重构-我应该关心吗?

[英]C# property refactoring - Should I care?

我有以下代码:

public class Header
{
    Line Lines { get { ...}}

    public ICryptographer GetCryptographer(FieldGroup group)
    {
        ...
    }
}

public class Line
{

    public Header Header { get; set; }
    public FieldGroup FieldGroup { get; set; }

    ICryptographer CryptoGrapher { get { return Header.GetCryptographer(FieldGroup); } }

    public decimal? Month1
    {
        get { return _month1; }
        set
        {
            if (_month1 != value)
                Month1_Enc = CryptoGrapher.Encrypt(_month1 = value);
        }
    }
    private decimal? _month1;

    protected byte[] Month1_Enc { get; set; }

    //The same repeated for Month2 to Month12
}

public interface ICryptographer
{
    byte[] Encrypt(decimal? value);
    decimal? DecryptDecimal(byte[] value);
}

public enum FieldGroup
{
   ...
}

不久,属性Month1到Month12的类型为小数? 在将其保存到数据库之前,应先对其进行加密。 我还有一些其他具有加密属性的类。 每个属性代码看起来都与我在此处显示的Month1完全相同。

理想情况下,我想要这样的东西:

Encrypted<decimal?> Month1 { get; set;}

但这是不可能的,因为每个对象可能具有不同的Cryptographer(对称密钥)。

有没有一种方法可以对其进行重构,以避免出现此类可重复的代码?
我应该关心这样的重复吗?

因此,对于每个加密的对象,您都需要引用父对象,对吗?

因此,我的第一个尝试是尝试在每次使用Encrypted的每种用法中获取对父级的引用。 我认为轻量级接口很适合这种工作:

public interface IHasEncryptedProperties
{
    string GetKey();
}

然后在不需要加密属性的类上实现它们

public class Line : IHasEncryptedProperties
{
    public string GetKey() { /* return instance-specific key; */ }
}

然后,在加密后,您需要传入父实例。

public class Encrypted<T>
{
    private IHasEncryptedProperties _parent;

    public Encrypted(IHasEncryptedProperties parent)
    {
        _parent = parent;
    }

    public T Value
    {
        get
        {
            var encryptor = GetEncryptor(_parent.GetKey());
            // encrypt and return the value
        }
    }
}

..

希望这可以帮助。 如果没有,请发表评论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM