[英]How do i check string to see if all characters are integers, that it is 8 characters in length and throw an argument for each?
Class student 和 main 僅供參考。在 try catch 塊中有兩個單獨的 s1.SNum = "string" 應該每個都拋出一個單獨的參數,但每次都拋出相同的參數,我沒有弄清楚.
class Student
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public Date BirthDate { get; private set; }
public Date catalog;
public string sNum;
}
這是我遇到問題的代碼。 我想有兩組為 sNum 拋出異常。 一個表示沒有所有數字,一個表示長度不為八。
public string SNum
{
get
{
return sNum;
}
set
{
foreach (char c in sNum)
{
int count = 0;
char charToCount = ',';
bool result = (SNum.All(Char.IsDigit));
if (result == false)
{
throw new ArgumentOutOfRangeException(nameof(SNum), value,
$"{nameof(SNum)} characters are not all integers.");
}
if (c == charToCount)
{
count++;
}
else if (count != 8) BOTH WILL THROW THIS ARGUMENT RIGHT NOW
{
throw new ArgumentOutOfRangeException(nameof(SNum), value,
$"{nameof(SNum)} length is not eight.");
}
}
}
和主要的 Class 參考 try catch..即使我正在檢查任何字母s1.SNum = "158945K9";
仍然會拋出與s1.SNum = "1234567";
// attempt to assign invalud sNum length
try
{
s1.SNum = "1234567";
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"{ex.Message}\n");
}
// attempt to assign invalud sNum character
try
{
s1.SNum = "158945K9";
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"{ex.Message}\n");
}
如果您只關心該值是所有數字並且長度為 8 個字符,那么實現比您所擁有的要簡單得多:
set
{
if (value.Any(ch => !char.IsDigit(ch))
throw new ArgumentException("All characters must be digits.");
if (value.Length != 8)
throw new ArgumentException("Value must be eight characters in length.");
sNum = value;
}
似乎還有更多的東西,但你還沒有解釋 rest。 如果您想允許逗號並且它們不包含在長度計算中,那么它將變為如下所示:
set
{
if (value.Any(ch => ch != ',' && !char.IsDigit(ch))
throw new ArgumentException("All characters must be digits or commas.");
if (value.Count(ch => ch != ',') != 8)
throw new ArgumentException("Value must contain eight digits.");
sNum = value;
}
您可能更喜歡使用All
而不是Any
,這在這兩種情況下也都有效,並避免了第二個代碼片段中的雙重否定,但在每種情況下仍需要完全相同數量的字符:
set
{
if (!value.All(ch => char.IsDigit(ch))
throw new ArgumentException("All characters must be digits.");
if (value.Length != 8)
throw new ArgumentException("Value must be eight characters in length.");
sNum = value;
}
和:
set
{
if (!value.All(ch => ch == ',' && char.IsDigit(ch))
throw new ArgumentException("All characters must be digits or commas.");
if (value.Count(ch => ch != ',') != 8)
throw new ArgumentException("Value must contain eight digits.");
sNum = value;
}
使用Any
還可以與其他if
語句保持更多的一致性,但這是一件非常小的事情。
另請注意,我拋出了ArgumentException
而不是ArgumentOutOfRangeException
。 在這種情況下,沒有特定范圍的有效值,因此您不應拋出表明存在的異常。 如果有一個范圍,那么您可以使用最小值和最大值來描述它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.