2017-04-05 37 views
-4

我目前正在學習考試,而我正在嘗試編寫一個類,我看到了這個需求的屬性。我需要在名爲User的類中編寫此屬性。在C中格式化屬性#

電話 - 必須在格式「+ [COUNTRY_CODE]/[電話]」,其中 [COUNTRY_CODE]爲1個3位和[電話]之間是數字8 和10之間。

  • 有效電話:+123/88888888,+1/1234579284

  • 無效電話:-123/88888888,+4分之1235 4444444,123348585313, 123 \ 34553363587

我是否使用[RegularExpression()]ComponentModel.DataAnnotations還是別的?

+0

請閱讀[問]。重要短語:「搜索和研究」和「解釋......阻止你自己解決它的任何困難」。 –

回答

0

我認爲這個代碼你想要做什麼:

private string _phone; 
public string Phone 
{ 
    get 
    { 
     return _phone; 
    } 
    set 
    { 
     int indexOfSlash = value.IndexOf("/"); 

     if (value.Length > 13 || indexOfSlash > 4 || indexOfSlash < 2 || value[0] != '+') 
      throw new Exception("Wrong format"); 

     for (int i = 1; i < value.Length; i++) 
     { 
      if ((i < indexOfSlash || i > indexOfSlash) && !value[i].IsDigit()) 
       throw new Exception("Wrong format"); 
     } 

     _phone = value; 
    } 
} 
+0

這段代碼是一個很好的例子,說明爲什麼使用正則表達式是合理的:一旦你熟悉語法,它們比這樣的代碼更好的閱讀和維護。 你可以簡化這個代碼: indexOfSlash> 4 || indexOfSlash < 2 => indexOfSlash!= 3 i indexOfSlash => i!= indexOfSlash 此外,如果電話號碼是空字符串,則代碼會崩潰。 –

0

你可以在電話setter方法需要使用正則表達式。

^\+\d{1,3}\/\d{8,10}$ 

打破下來:

  • ^:僅匹配字符串的開頭。
  • \+:匹配+,這需要被轉義。
  • \d{1,3}:匹配1至3次的任何數字(0-9)。
  • \/:匹配/,這需要轉義。
  • \d{8,10}:匹配從8到10次的任何數字(0-9)。
  • $:僅在字符串末尾匹配。

示例代碼:

private static Regex phoneRegex = new Regex(@"^\+\d{1,3}\/\d{8,10}$", RegexOptions.Compiled); 

private string phone; 
public string Phone { 
    get { return phone; } 
    set { 
     Match match = phoneRegex.Match(value); 
     if (match.Success) { 
      phone = value; 
     } else { 
      throw new ArgumentException("value"); 
     } 
    } 
}