typeof() when Cannot implicitly convert type 'System.Type' to 'string'

StackOverflow https://stackoverflow.com/questions/17915943

  •  04-06-2022
  •  | 
  •  

سؤال

I'm doing some Xml Serialization, and I'm getting a compile item error.

The code with the error is:

public class EPubBody
{
    [XmlElement(ElementName = "Image", DataType = typeof(EPubImage))]
    public object[] BodyItems;
}

The error is on the typeof(EPubImage) part. The error is Cannot implicitly convert type 'System.Type' to 'string'.

The class EPubImage is in the same namspace, and looks like this:

public class EPubImage
{
    [XmlAttribute("imagePath")]
    public string ImagePath { get; set; }

}

I guess typeof(EPubImage) is returning a System.Type instead of an string. Any pointers on how to ensure that the typeof statement will return a string, instead of a System.Type?

هل كانت مفيدة؟

المحلول 2

The MSDN Documentation for XmlElementAttribute clearly states that DataType is string, whereas the Type property is of Type.

نصائح أخرى

According to the documentation, the DataType property is used to specify an XSD data type, not a .NET type:

An XML Schema data type, as defined by the World Wide Web Consortium (www.w3.org) document named "XML Schema Part 2: Datatypes".

Try this instead:

public class EPubBody
{
    [XmlElement(ElementName = "Image")]
    public EPubImage[] BodyItems;
}

I found an override for XmlElement() for XmlElement(string, Type), so I tried this instead, and it works.

public class EPubBody
{
    [XmlElement("image", typeof(EPubImage))]
    public object[] BodyItems;
}

When I say "it works", I mean I no longer the the compile time error. Having it exhibit the behaviour as seen in the Remarks section of this document, is another issue.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top