2014-03-31 92 views
3

我可以在另一個類中繼承「密碼」數據註釋嗎?是否有可能在C#中繼承數據註釋?

public class AccountCredentials : AccountEmail 
{ 
    [Required(ErrorMessage = "xxx.")] 
    [StringLength(30, MinimumLength = 6, ErrorMessage = "xxx")] 
    public string password { get; set; } 
} 

其他類:

public class PasswordReset : AccountCredentials 
{ 
    [Required] 
    public string resetToken { get; set; } 
    **["use the same password annotations here"]** 
    public string newPassword { get; set; } 
} 

我不得不使用不同的模型,由於API調用的,但想避免維持同一領域兩個定義。 謝謝!

增加:像

[UseAnnotation[AccountCredentials.password]] 
public string newPassword { get; set; } 
+0

如果你定義了一個新的屬性 - 你認爲魔法繼承可能會成爲可能嗎?那不是繼承,那將是神奇的。神奇地知道一個新的屬性的編譯器與舊的相關。 – TomTom

+0

對不起,也許我沒有把它定義得足夠好。我寧願想,會出現像[使用[AccountCredentials.passwordAnnotation]] – jens

+0

他引用這個事實'AccountCredentials'中的屬性是'password',並且您希望新類PasswordReset的屬性'newPassword'繼承來自'AccountCredential'的'password'屬性的數據。所以他問你,當你在第二類中定義一個全新的屬性時,你認爲繼承會發生什麼。 –

回答

4

考慮favoring composition over inheritance並使用Money Pattern

public class AccountEmail { } 

    public class AccountCredentials : AccountEmail 
    { 
     public Password Password { get; set; } 
    } 

    public class PasswordReset : AccountCredentials 
    { 
     [Required] 
     public string ResetToken { get; set; } 

     public Password NewPassword { get; set; } 
    } 

    public class Password 
    { 
     [Required(ErrorMessage = "xxx.")] 
     [StringLength(30, MinimumLength = 6, ErrorMessage = "xxx")] 
     public string Value { get; set; } 

     public override string ToString() 
     { 
      return Value; 
     } 
    } 

或許它已經成爲我的黃金錘,但最近我已經有很多這種成功的,給予創建一個基類或不要採取有共同的行爲,並在封裝它之間的選擇尤其是當目的。繼承可能會很快失去控制。

0

在基礎類,你可以把它virtual財產,並改變它override在派生類中。但是,它不會繼承屬性,我們做一個棘手的位置: