繁体   English   中英

如何将现有枚举作为 WCF 服务参数传递?

[英]How to pass existing enum as WCF Service parameter?

我想将枚举类型值传递给我的 WCF 服务。 但是,这个枚举类型(例如SqlDbType )不是我创建的,我无法修改它。 在google上搜索后,我了解到作为WCF Service参数传递的枚举类型必须添加DataContractAttribute并且必须添加其成员EnumMemberAttribute ,我想知道是否可以在运行时进行此工作,例如在服务启动时。 这是我的代码不起作用:

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);
        }
    }
}

如何从另一个枚举中重新创建自己的枚举,并根据需要向前者添加相关属性。 我知道这不是运行时解决方案,但它很简单,可以在几分钟内完成。

考虑以下第 3 方枚举:

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

以这种方式创建自己的一个:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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