gpt4 book ai didi

.net - WCF 版本控制枚举

转载 作者:行者123 更新时间:2023-12-02 12:11:59 24 4
gpt4 key购买 nike

我正在开始编写一些需要向前兼容和版本控制的 WCF 数据协定。我一直在阅读MSDN文章here ,并且想知道是否有人对有关枚举的第 14 点有澄清。内容如下:

14. You should not add or remove enumeration members between versions. You should also not rename enumeration members, unless you use the Name property on the EnumMemberAttribute attribute to keep their names in the data contract model the same.

读到这里,我认为这意味着一旦枚举被发布(并被客户端使用),你就不能在不破坏兼容性的情况下以任何方式修改它(主要是添加/删除)? (即这将是一个重大变化)

有人可以证实这一点吗?

最佳答案

我建议不要通过 WCF 接口(interface)发送枚举。假设您有以下枚举:

[DataContract]
public enum WeekdayEnum
{
[EnumMember]
Monday = 0
}

如果您通过 WCF 返回枚举,一切都会正常运行:

[ServiceContract]
public class Service1
{
[OperationContract]
public List<WeekdayEnum> GetWeekdays()
{
return new List<WeekdayEnum> { WeekdayEnum.Monday };
}
}

添加到枚举而不更新客户端中的服务引用,仍然没问题:

[DataContract]
public enum WeekdayEnum
{
[EnumMember]
Monday = 0,
[EnumMember]
Tuesday = 1
}

但是,如果您从服务返回附加值而不更新客户端服务引用,旧版客户端将会中断:

[ServiceContract]
public class Service1
{
[OperationContract]
public List<WeekdayEnum> GetWeekdays()
{ // NetDispatcherFaultException on legacy clients that only have Monday
return new List<WeekdayEnum> { WeekdayEnum.Monday, WeekdayEnum.Tuesday };
}
}

在支持旧客户非常重要的项目中,我遇到了这方面的问题。解决方案是简单地通过 WCF 发送 DTO,而不是枚举。例如。 WeekdayEnum 可以通过通过简单的 DTO 发送值来替换:

[DataContract]
public class WeekdayDto
{
[DataMember]
public int Id { get; set; }

[DataMember]
public string Name { get; set; }
}

这样,您的老客户就会保持满意。

关于.net - WCF 版本控制枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4677876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com