Ada 程式設計/屬性/'Val
外觀
'Val 屬性為所有離散型別定義。它是一個函式,返回 S 基型別的那個值,該值具有引數的位置編號;字首 S 必須是子型別名稱。(任何特定整數型別都隱式轉換為universal_integer。)
functionS'Val (Arg: universal_integer)returnS'Base;
如果 S 型別中沒有值具有 Arg 的位置編號,則會引發 Constraint_Error 異常。
請注意,表示子句不會影響位置編號。列舉值具有什麼底層值,位置編號將保持不變。
-- Declare a discrete type; the compiler will assign the internal representation as 0 .. 2 -- identical to the position numbers.typeMy_Enumis(Enum1, Enum2, Enum3); -- Declare a discrete type and explicitly set the internal representation. -- Note that the position numbers are still 0 .. 2.typeMy_Other_Enumis(Value1, Value2, Value3);forMy_Other_Enumuse(Value1 => 2, Value2 => 4, Value3 => 6);pragmaAssert (My_Enum'Val(0) = Enum1); -- OKpragmaAssert (My_Enum'Val(1) = Enum2); -- OKpragmaAssert (My_Enum'Val(2) = Enum3); -- OKpragmaAssert (My_Other_Enum'Val(0) = Value1); -- OKpragmaAssert (My_Other_Enum'Val(1) = Value2); -- OKpragmaAssert (My_Other_Enum'Val(2) = Value3); -- OKpragmaAssert (My_Enum'Val(3) = Enum3); -- WrongpragmaAssert (My_Other_Enum'Val(2) = Value1); -- WrongpragmaAssert (My_Other_Enum'Val(4) = Value2); -- WrongpragmaAssert (My_Other_Enum'Val(6) = Value3); -- Wrong
其他示例
typeColoris(RED, BLUE, WHITE); OBJECT : Color := WHITE;beginPut (Color'Val (1)); -- give BLUE
內部表示只能透過 Unchecked_Conversion 查詢。
'Val 屬性的逆是 'Pos。
- 13.3 操作和表示屬性 (註釋)
- 附錄 K 語言定義的屬性 (註釋)
