WCF Datacontract免费序列化(3.5 SP1)
时间:2020-03-05 18:53:31 来源:igfitidea点击:
有人有这个实际工作吗?没有有关如何启用此功能的文档,尽管有3.5 SP1项目,但缺少属性异常。
解决方案
回答
WCF中有几个序列化选项:数据协定,XML序列化和原始数据有效负载。我们想使用其中哪些?从这个问题来看,我们似乎正在尝试使用除装饰有datacontact属性的对象之外的其他东西。那是你在问什么吗?
回答
是的,我正在尝试使用SP1(http://www.pluralsight.com/community/blogs/aaron/archive/2008/05/13/50934.aspx)中宣布的无属性序列化。该死的,如果我能使它正常工作,并且没有文档。
回答
我让它可以在测试应用程序上工作...
服务定义:
[ServiceContract] public interface IService1 { [OperationContract] CompositeType GetData(int value); } public class CompositeType { bool boolValue = true; string stringValue = "Hello "; public bool BoolValue { get { return boolValue; } set { boolValue = value; } } public string StringValue { get { return stringValue; } set { stringValue = value; } } }
服务实施:
public class Service1 : IService1 { public CompositeType GetData(int value) { return new CompositeType() { BoolValue = true, StringValue = value.ToString() }; } }
回答
尽管我将所有内容都添加到了已知类型列表中,但是我对抽象基类的使用可能使事情变得混乱。
回答
是的,它可能与抽象类和继承有关。有时可能会使序列化混乱。此外,如果所有内容都不公开,则也可以查看类和类层次结构。
回答
我发现它不适用于内部/私有类型,但是将我的类型公开就可以了。这意味着也没有匿名类型:(
使用反射器,我发现了似乎在做决定的方法ClassDataContract.IsNonAttributedTypeValidForSerialization(Type)。这似乎是最后的杀手,该类型必须可见,因此不允许内部/私有类型:(
internal static bool IsNonAttributedTypeValidForSerialization(Type type) { if (type.IsArray) { return false; } if (type.IsEnum) { return false; } if (type.IsGenericParameter) { return false; } if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) { return false; } if (type.IsPointer) { return false; } if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) { return false; } foreach (Type type2 in type.GetInterfaces()) { if (CollectionDataContract.IsCollectionInterface(type2)) { return false; } } if (type.IsSerializable) { return false; } if (Globals.TypeOfISerializable.IsAssignableFrom(type)) { return false; } if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) { return false; } if (type == Globals.TypeOfExtensionDataObject) { return false; } if (type.IsValueType) { return type.IsVisible; } return (type.IsVisible && (type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, Globals.EmptyTypeArray, null) != null));
}