2009-11-08 69 views
1

我有以下代碼:C#屬性重構 - 我應該關心嗎?

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;} 

但這是不可能的,因爲每個對象可能有不同的密碼學家(對稱密鑰)。

有沒有一種方法來重構它以避免這種可重複的代碼?
我應該關心這種重複嗎?

回答

0

因此,對於每個加密你需要一個父母的引用,我是我正確的?

因此,我第一次嘗試將嘗試獲得對每個加密的第一次使用的父母的引用。我認爲輕量級接口是很好的這樣的工作:

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 
     } 
    } 
} 

..

希望這有助於。如果沒有,請留下評論。

+0

我想過這樣的方式,但如果我想用新值設置Month1,則需要設置父級。我可以在兩個地方做到這一點1)在使用更糟糕的Line實例的代碼中,我必須在每個地方記住它。 2)在類似於我現在使用的代碼量的Month1 setter方法中。 – SeeR 2009-11-08 23:56:51

+0

@SeeR您可以將轉換運算符從T重載到以獲得屬性設置器部分,但我不確定。當我有時間時,將回到它並更新這篇文章。 – chakrit 2009-11-09 01:16:11

+0

在轉換運算符中,我沒有關於父類的信息(除非我使用一些靜態字段 - 在這種情況下我不能這樣做) – SeeR 2009-11-09 07:56:27

相關問題