typeof()时无法隐式转换类型';System.Type';到';字符串';

本文关键字:System Type 字符串 类型 转换 typeof | 更新日期: 2023-09-27 18:25:13

我正在进行一些Xml序列化,并且收到一个编译项错误。

错误代码为:

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

错误出现在typeof(EPubImage)部分。错误为Cannot implicitly convert type 'System.Type' to 'string'

EPubImage在同一个命名空间中,看起来像这样:

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

我猜typeof(EPubImage)返回的是System.Type而不是string。有关于如何确保typeof语句将返回字符串而不是System.Type的指针吗?

typeof()时无法隐式转换类型';System.Type';到';字符串';

根据文档,DataType属性用于指定XSD数据类型,而不是.NET类型:

一种XML模式数据类型,由万维网联盟(www.w3.org)文件"XML模式第2部分:数据类型"定义。

试试这个:

public class EPubBody
{
    [XmlElement(ElementName = "Image")]
    public EPubImage[] BodyItems;
}
XmlElementAttribute的MSDN文档明确指出DataTypestring,而Type属性是Type

我为XmlElement(string,Type)找到了XmlElement()的重写,所以我尝试了这个方法,它有效。

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

当我说"它有效"时,我的意思是我不再是编译时的错误。让它表现出本文件备注部分所示的行为是另一个问题。