枚举和常数组映射

From Apache OpenOffice Wiki
< Zh‎ | Documentation
Revision as of 02:54, 14 May 2009 by Jirong (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search



使用符合命名规则的名称对枚举类型的值进行寻址。以下示例假定 oExampleoExample2 支持 com.sun.star.beans.XPropertySet,并包含一个枚举类型为 com.sun.star.beans.PropertyState 的属性 Status:

 Dim EnumValue
 EnumValue = com.sun.star.beans.PropertyState.DEFAULT_VALUE
 MsgBox EnumValue ' displays 1
 
 eExample.Status = com.sun.star.beans.PropertyState.DEFAULT_VALUE


Basic 不支持枚举类型。在 Basic 中,来自 UNO 的枚举值被转换成 Long 值。只要 Basic 知道某个属性或某个接口方法参数是否需要一个枚举类型,就在内部将 Long 值转换为适当的枚举类型。当接口访问方法需要一个 Any

 Dim EnumValue
 EnumValue = oExample.Status ' EnumValue is of type Long
 
 ' Accessing the property implicitly
 oExample2.Status = EnumValue ' Ok! EnumValue is converted to the right enum type
 
 ' Accessing the property explicitly using XPropertySet methods
 oExample2.setPropertyValue( "Status", EnumValue ) ' WRONG! Will probably fail!


显式访问会失败,因为 EnumValue 是作为 Any 类型的参数传递到 setPropertyValue(),因此,Basic 不知道实际需要一个 PropertyState 类型的值。还有一个问题,在 Basic 中,com.sun.star.beans.PropertyState 的类型为 Long。此问题在 com.sun.star.beans.XPropertySet 接口的实现中得以解决。对于枚举类型,使用 Basic 属性语法 Object.Property 来访问隐式属性优于使用类型 Any 来调用普通方法。如果仅存在需要 Any 类型的 enum 变量的普通接口方法,则没有适用于 Basic 的解决方案。


常数组用于在 IDL 中指定一组常数值。在 Basic 中,可以使用其全限定名称访问这些常数。以下代码显示了 com.sun.star.beans.PropertyConcept 中的一些常数:

 MsgBox com.sun.star.beans.PropertyConcept.DANGEROUS ' Displays 1
 MsgBox com.sun.star.beans.PropertyConcept.PROPERTYSET ' Displays 2


可以将常数组或枚举指定给对象。如果需要访问多个枚举或常数值,使用此方法可以缩短代码:

 Dim oPropConcept
 oPropConcept = com.sun.star.beans.PropertyConcept
 msgbox oPropConcept.DANGEROUS ' Displays 1
 msgbox oPropConcept.PROPERTYSET ' Displays 2


Content on this page is licensed under the Public Documentation License (PDL).
Personal tools
In other languages