我正在使用以下代碼行來檢查小數是否相等,但它顯示語法錯誤。檢查一些十進制值是否相等
if (ProgramVariables.MSR_AR_System == ProgramVariables.MSR_AR_EB_1 == ProgramVariables.MSR_AR_EB_2 == ProgramVariables.MSR_AR_EB_3)
什麼是正確的方法?
我正在使用以下代碼行來檢查小數是否相等,但它顯示語法錯誤。檢查一些十進制值是否相等
if (ProgramVariables.MSR_AR_System == ProgramVariables.MSR_AR_EB_1 == ProgramVariables.MSR_AR_EB_2 == ProgramVariables.MSR_AR_EB_3)
什麼是正確的方法?
它應該是:
if (ProgramVariables.MSR_AR_System == ProgramVariables.MSR_AR_EB_1
&& ProgramVariables.MSR_AR_EB_1 == ProgramVariables.MSR_AR_EB_2
&& ProgramVariables.MSR_AR_EB_2 == ProgramVariables.MSR_AR_EB_3)
你不能只是做A == B == C == D
。你必須使用&&
(AND)運算符,就像這樣:
if (a == b && b == c && c == d && d == e)
{
// Do something
}
這意味着if a equals b AND b equals c AND c equals d AND d equals e then
。
爲什麼會發生這種情況?因爲equality operator需要兩個相同類型的參數。 a == b
結果在布爾(true
或false
),你這個結果比較的c
下一個值這仍然是decimal
類型的,你不能比較一個boolean
到decimal
因爲它們是同一類型的不行。
==
運算符是二元運算符,從左到右進行求值。這意味着,它計算第一
ProgramVariables.MSR_AR_System == ProgramVariables.MSR_AR_EB_1
其給出一個布爾值,然後該布爾值與
(true or false) == ProgramVariables.MSR_AR_EB_2
這又給出了一個布爾值,然後該第二布爾值與
(true or false) == ProgramVariables.MSR_AR_EB_3
由於您比較了不兼容類型的值,所以出現錯誤。
正確的方法來比較多個值,是對他們的邏輯&&
(和)運營商,合併例如
if (ProgramVariables.MSR_AR_System == ProgramVariables.MSR_AR_EB_1
&& ProgramVariables.MSR_AR_System == ProgramVariables.MSR_AR_EB_2
&& ProgramVariables.MSR_AR_System == ProgramVariables.MSR_AR_EB_3)
試試這個
if (ProgramVariables.MSR_AR_System.Equals(ProgramVariables.MSR_AR_EB_1).Equals(ProgramVariables.MSR_AR_EB_2.Equals(ProgramVariables.MSR_AR_EB_3)))
比較符返回布爾值,即真或假。因此,第一次比較返回布爾值,並且您將與小數進行比較。因此錯誤。
您可以編寫方法是這樣的:
public static bool AllEqual<T>(params T[] values)
where T : struct
{
if (values.Length < 2)
return true;
T first = values[0];
for (int i = 1; i < values.Length; i++)
{
if (!values[i].Equals(first))
return false;
}
return true;
}
並用它來比較所有值:
if (AllEqual(ProgramVariables.MSR_AR_System,
ProgramVariables.MSR_AR_EB_1,
ProgramVariables.MSR_AR_EB_2,
ProgramVariables.MSR_AR_EB_3))
對於某些包圍,這將是合法的,但不能表達你的意圖(如果我沒有理解你的意圖是否正確)。如果你完成了'((Sys == 1)==(2 == 3))',它會編譯,但不能確保所有四個變量是相等的。 –