【发布时间】: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))],所以我还没有尝试过你的答案。我认为您的回答很好,并且相信它会起作用,但在我的情况下它需要更多代码。