I have two classes as below:
public class BaseClass
{
public BaseClass() { }
public BaseClass(string name)
{
this._name = name;
}
private string _name = "BaseClass";
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
}
public class InheritedClass : BaseClass
{
public InheritedClass(string name)
: base(name)
{
}
}
then i write a webmethod to use the classes.
public class MyServices : WebService
{
[WebMethod]
public BaseClass HelloWorld()
{
return new InheritedClass("FirstClass");
}
}
now I get an error:
System.InvalidOperationException: There was an error generating the XML
document. ---> System.InvalidOperationException: The type InheritedClass was
not expected. Use the XmlInclude or SoapInclude attribute to specify types
that are not known statically.
at
Microsoft.Xml.Serialization.GeneratedAssembly.XmlS erializationWriter1.Write2
_BaseClass(String n, String ns, BaseClass o, Boolean isNullable, Boolean
needType)
at
Microsoft.Xml.Serialization.GeneratedAssembly.XmlS erializationWriter1.Write3
_BaseClass(Object o)
at
Microsoft.Xml.Serialization.GeneratedAssembly.Base ClassSerializer.Serialize(
Object objectToSerialize, XmlSerializationWriter writer)
at System.Xml.Serialization.XmlSerializer.Serialize(X mlWriter xmlWriter,
Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String
id)
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Serialize(X mlWriter xmlWriter,
Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String
id)
at System.Xml.Serialization.XmlSerializer.Serialize(T extWriter textWriter,
Object o)
at System.Web.Services.Protocols.XmlReturnWriter.Writ e(HttpResponse
response, Stream outputStream, Object returnValue)
at System.Web.Services.Protocols.HttpServerProtocol.W riteReturns(Object[]
returnValues, Stream outputStream)
at System.Web.Services.Protocols.WebServiceHandler.Wr iteReturns(Object[]
returnValues)
at System.Web.Services.Protocols.WebServiceHandler.In voke()
I know I can solve the problem by adding this line before the MyServices
[XmlInclude(typeof(InheritedClass))]
But I can't confirm how many "inherited classes" there are in my code, so it
seems not fit for me.
Could you show me another way?Thank you.