【问题标题】:How to pass existing enum as WCF Service parameter?如何将现有枚举作为 WCF 服务参数传递?
【发布时间】:2020-03-17 23:01:48
【问题描述】:

我想将枚举类型值传递给我的 WCF 服务。但是这个枚举类型(例如SqlDbType)不是我创建的,我不能修改它。在google上搜索后得知,作为WCF服务参数传递的枚举类型必须添加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);
        }
    }
}

【问题讨论】:

  • 只需传递 int 和 cast,全部排序了吗?我个人认为枚举只是序列化。不过也许你可以试试[ServiceKnownType(typeof(MyEnum))]
  • @MichaelRandall,我将枚举值存储在字典中作为值,如果传递int,我怎么知道它是枚举类型还是int类型?
  • 如果dictionary<string, object> 工作,我会感到惊讶。
  • @V.S.抱歉这么晚才回复。自从我上次查看这篇文章已经过去几个月了,我记得我用另一种方式解决了我的问题:在 ServiceContract 上使用 [ServiceKnownType(typeof(MyEnum))],在 DataContract 上使用 [KnownType(typeof(MyEnum))],所以我还没有尝试过你的答案。我认为您的回答很好,并且相信它会起作用,但在我的情况下它需要更多代码。

标签: c# wcf


【解决方案1】:

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

考虑以下第 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
}

【讨论】:

    猜你喜欢
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多