简体   繁体   中英

How to pass existing enum as WCF Service parameter?

I want to pass enum type value to my WCF Service. However this enum type(for example SqlDbType ) is not created by me and I can't modify it. After searching on google, I learn that enum type passed as WCF Service parameter must be added DataContractAttribute and its member must be added EnumMemberAttribute , I wonder if it's possible to do this work at runtime, for example, when service starts. Here is my code which is not working:

public class AppInitializer
{
    public static void AppInitialize()
    {
        Type enumType = typeof(SqlDbType);
        Attribute[] dataContractAttribute = { new DataContractAttribute()};
        TypeDescriptor.AddAttributes(enumType, dataContractAttribute);
        Attribute[] enumMemberAttribute = { new EnumMemberAttribute() };
        foreach (object value in Enum.GetValues(enumType))
        {
            TypeDescriptor.AddAttributes(value, enumMemberAttribute);
        }
    }
}

How about recreating your own enum out of the other one and add relevant attributes to the former as needed. I know this is not a runtime solution, but it is easy enough and could be done within a couple of minutes.

Considering the following 3rd party enum:

enum ThirPartyEnum
{
    Zero = 0,
    One = 1,
    Two = 2
}

Create your own one that way:

[DataContract(Name = "MyEnum")]
enum MyEnum
{
    [Description("Zero")]
    [EnumMember]
    Zero= ThirPartyEnum.Zero,

    [Description("One")]
    [EnumMember]
    One = ThirPartyEnum.One,

    [Description("Two")]
    [EnumMember]
    Two = ThirPartyEnum.Two
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM