Ada 程式設計/屬性/'Valid
外觀
Valid 屬性 可以與任何標量型別(即數字或列舉型別)的物件一起使用,以確定其值是否有效(例如,不在範圍之外等)。結果始終為 True 或 False;不會引發 Constraint_Error 或任何其他 異常。
重要的是,屬性的計算不計入讀取物件,而讀取無效物件會使程式出現錯誤。
-- Declare a discrete type and explicitly set the position numberstypeMy_Enumis(Value1, Value2, Value3);forMy_Enumuse(Value1 => 2, Value2 => 4, Value3 => 6 ); Result : Natural; Enum_Var, Other_Var: My_Enum; Sneaky_Back_Door : Integer;forEnum_Var'AddressuseSneaky_Back_Door'Address; ...ifnotResult'Validthen-- Result is out-of-range, it has a negative value Result := Natural'First;endif; ... -- Assign a bad integer value to the enumerated type variable. Sneaky_Back_Door := 1; Other_Var := Enum_Var; -- reading Enum_Var makes the program erroneous ...ifnotEnum_Var'Validthen-- this is not reading -- Enum_Var contains a bad value Enum_Var := My_Enum'First;endif;
請注意,在上面的錯誤賦值語句中,由於兩個變數都是相同子型別的,因此沒有執行範圍檢查(因此不會引發異常)。
- 5.9.1 未經檢查的轉換 — 考慮使用 'Valid 屬性來檢查標量資料的有效性。
- 5.9.7 Direct_IO 和 Sequential_IO — 使用 'Valid 屬性來檢查透過 Ada.Direct_IO 和 Ada.Sequential_IO 獲得的標量值的有效性。
- 6.3.3 Abort 語句 — 在存在 Abort 語句的情況下,考慮使用 'Valid 屬性來檢查標量資料的有效性。
