gpt4 book ai didi

c# - 为什么我不能在同一个类上使用 WCF DataContract 和 ISerializable?

转载 作者:可可西里 更新时间:2023-11-01 08:45:49 25 4
gpt4 key购买 nike

我有一个类需要能够序列化为 SQLServer session 变量并可通过 WCF 服务使用。我声明如下

namespace MyNM
{
[Serializable]
[DataContract(Name = "Foo", Namespace = "http://www.mydomain.co.uk")]

public class Foo : IEntity, ISafeCopy<Foo>
{
[DataMember(Order = 0)]
public virtual Guid Id { get; set; }

[DataMember(Order = 1)]
public virtual string a { get; set; }

DataMember(Order = 2)]
public virtual Bar c { get; set; }

/* ISafeCopy implementation */
}


[Serializable]
[DataContract(Name = "Bar ", Namespace = "http://www.mydomain.co.uk")]
public class Bar : IEntity, ISafeCopy<Bar>
{
#region Implementation of IEntity

DataMember(Order = 0)]
public virtual Guid Id { get; set; }
[DataMember(Order = 1)]
public virtual Baz y { get; set; }

#endregion

/* ISafeCopy implementation*/
}


[Serializable]
[DataContract]
public enum Baz
{
[EnumMember(Value = "one")]
one,
[EnumMember(Value = "two")]
two,
[EnumMember(Value = "three")]
three
}

但是当我尝试调用此服务时,我在跟踪日志中收到以下错误。

"System.Runtime.Serialization.InvalidDataContractException: Type 'BarProxybcb100e8617f40ceaa832fe4bb94533c' cannot be ISerializable and have DataContractAttribute attribute."

如果我去掉 Serializable 属性,WCF 服务可以工作,但是当对象不能序列化到 session 时。如果我从 Bar 类中删除 DataContract 属性,WCF 服务将失败并显示

Type 'BarProxy3bb05a31167f4ba492909ec941a54533' with data contract name 'BarProxy3bb05a31167f4ba492909ec941a54533:http://schemas.datacontract.org/2004/07/' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer

我已经尝试将 KnownType 属性添加到 foo 类中

[KnownType(typeof(Bar))]

但我仍然得到同样的错误。

谁能帮我解决这个问题?

非常感谢

戴夫

最佳答案

MSDN 上的这个问题可能有帮助:DataContract versus Serializable .

该线程接受的答案:

  1. [DataContract] and [Serializable] can be used together.

  2. DataContractSerializer understands both of them. If the type is marked with both of them, it will take the projection of [DataContract]

  3. Here are the docs on data transfer and serialization in WCF which provide a lot of detail on the serializers and known type: Data Transfer and Serialization

关于c# - 为什么我不能在同一个类上使用 WCF DataContract 和 ISerializable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2461466/

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