Change is constant - 变化时唯一的永恒

在WCF中使用Flag Enumerations

 

请看MSDN示例:

 

复制代码
[DataContract][Flags]
public enum CarFeatures
{
    None = 0,
    [EnumMember]
    AirConditioner = 1,
    [EnumMember]
    AutomaticTransmission = 2,
    [EnumMember]
    PowerDoors = 4,
    AlloyWheels = 8,
    DeluxePackage = AirConditioner | AutomaticTransmission | PowerDoors | AlloyWheels,
    [EnumMember]
    CDPlayer = 16,
    [EnumMember]
    TapePlayer = 32,
    MusicPackage = CDPlayer | TapePlayer,
    [EnumMember]
    Everything = DeluxePackage | MusicPackage
}
复制代码

 

注意以下几点:

1. 请使用[Flags]标志。

2.所有应用了EnumMemberAttribute的枚举成员值必须是不间断的2的幂 (如 1, 2, 4, 8, 16, 32, 64).

3.如果通过数值来找枚举成员(比如通过4 来找PowerDoors),会先判断是否存在这个成员,不存在则判断是否存在这样的组合成员,如果仍然不存在且数值不为0的话则会抛出SerializationException,如果数值为0则返回空列表。

4.未标记为[EnumMember]的成员,在WCF客户端不能使用,如上例中的None = 0。

详细用法请见MSDN介绍。

http://msdn.microsoft.com/en-us/library/aa347875.aspx

 

You can use simple enumerations when you do not need to customize the enumeration's data contract name and namespace and the enumeration member values.

Notes on Simple Enumerations

Applying the EnumMemberAttribute attribute to simple enumerations has no effect.

It makes no difference whether or not the SerializableAttribute attribute is applied to the enumeration.

The fact that the DataContractSerializer class honors the NonSerializedAttribute attribute applied to enumeration members is different from the behavior of the BinaryFormatter and the SoapFormatter. Both of those serializers ignore theNonSerializedAttribute attribute.

Flag Enumerations

You can apply the FlagsAttribute attribute to enumerations. In that case, a list of zero or more enumeration values can be sent or received simultaneously.

To do so, apply the DataContractAttribute attribute to the flag enumeration and then mark all the members that are powers of two with the EnumMemberAttribute attribute. Note that to use a flag enumeration, the progression must be an uninterrupted sequence of powers of 2 (for example, 1, 2, 4, 8, 16, 32, 64).

The following steps apply to sending a flag's enumeration value:

  1. Attempt to find an enumeration member (with the EnumMemberAttribute attribute applied) that maps to the numeric value. If found, send a list that contains just that member.
  2. Attempt to break the numeric value into a sum such that there are enumeration members (each with the EnumMemberAttribute attribute applied) that map to each part of the sum. Send the list of all these members. Note that thegreedy algorithm is used to find such a sum, and thus there is no guarantee that such a sum is found even if it is present. To avoid this problem, make sure that the numeric values of the enumeration members are powers of two.
  3. If the preceding two steps fail, and the numeric value is nonzero, throw a SerializationException. If the numeric value is zero, send the empty list.
posted @ 2016-03-29 09:41  人海灬  阅读(237)  评论(0编辑  收藏  举报