简体   繁体   English

序列化系统对象

[英]Serialization system.object

I'm trying to create a webservice to return a generic. 我正在尝试创建一个Web服务以返回泛型。 The return class looks like this: 返回类如下所示:

[Serializable]
public class RenderReturn
{
    public RenderReturnStatus StatusReturn { get; set; }
    public string MessageReturn { get; set; }
    public string MessageTitle { get; set; }
    public object **ObjectReturn** { get; set; }
}

Where ObjectReturn can be an object or a list of application objects, like cars, customers, etc.. 其中ObjectReturn可以是对象或应用程序对象列表,例如汽车,客户等。

But the webservice returns the following error: 但是,Web服务返回以下错误:

System.InvalidOperationException: There was an error generating the XML document. --->
System.InvalidOperationException: The type Environment was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
   at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType)

This is possible or method should always return specific types? 这是可能的还是方法应始终返回特定类型?

Explicitly name your types. 明确命名您的类型。 Otherwise one can put something in that isn't serializable. 否则,可以放入无法序列化的内容。

Type of object is too generic for .NET to know what kind of object it is dealing with and how to deserialise. 对于.NET, object类型太笼统,无法知道它正在处理哪种对象以及如何反序列化。 So it asks you to give it some hint by using XmlInclude attributes telling .NET the types to expect. 因此,它要求您通过使用XmlInclude属性告诉.NET所需的类型来给它一些提示。 In WCF you do the same: you use KnownType attribute to decorate properties. 在WCF中,您执行相同的操作:使用KnownType属性来装饰属性。

Type object is not a good candidate for DTO objects that need to cross process boundaries. 对于需要跨越过程边界的DTO对象,类型object不是很好的选择。

In WCF or Web Services, try not to think in object-oriented fashion but think in WSDL. 在WCF或Web服务中,请不要以面向对象的方式思考,而应以WSDL的方式思考。 As far as WSDL is concerned you have a contract which explicitly defines the type of messages passed between client and server. 就WSDL而言,您有一个合同 ,该合同明确定义了客户端和服务器之间传递的消息类型。

Try something along these lines: 尝试以下方法:

public class RenderReturn<T>
{
  public T ObjectReturn {get;set;}
}

That way, at run-time, you'll have a concrete type rather than just System.Object. 这样,在运行时,您将拥有一个具体的类型,而不仅仅是System.Object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM