【问题标题】:typeof() when Cannot implicitly convert type 'System.Type' to 'string'typeof() 无法将类型“System.Type”隐式转换为“字符串”时
【发布时间】:2013-07-29 04:14:49
【问题描述】:

我正在做一些 Xml 序列化,我得到一个编译项错误。

出现错误的代码是:

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

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

EPubImage 类在同一个 namspace 中,如下所示:

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

}

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

【问题讨论】:

  • 可能是typeof(EPubImage).ToString()
  • DataType 很可能需要一个字符串,而不是一个类型。尝试使用 EPubImage 的完全限定名称。
  • @Tim 我虽然说它期望 string 这意味着它想要一个 32 位整数。那我一定是错的。
  • @Tim 不能开个玩笑?
  • @ColeJohnson - 当然,我可以开个玩笑;当它清楚时,这是一个笑话。我以为你在发表幽默的评论,但我不是 100% 确定,因此我的“嗯”:)

标签: c# typeof


【解决方案1】:

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

一种 XML Schema 数据类型,由万维网联盟 (www.w3.org) 文档定义,名为“XML Schema Part 2: Datatypes”。

试试这个:

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

【讨论】:

【解决方案2】:

MSDN Documentation for XmlElementAttribute 明确指出DataTypestring,而Type 属性是Type

【讨论】:

  • 我想我是被msdn.microsoft.com/en-us/library/…的备注中的例子误导了
  • 有什么我可以做的覆盖,以便 typeof(EPubImage) 将返回一个字符串?
  • No.. 你在属性中需要的是一个编译时常量。这不是返回 string 的运算符/函数所提供的。它返回任何东西的简单事实意味着它可以是可变的(因为C#没有constness的概念)。
【解决方案3】:

我为 XmlElement(string, Type) 找到了 XmlElement() 的覆盖,所以我尝试了这个,它可以工作。

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

当我说“它有效”时,我的意思是我不再出现编译时错误。让它表现出Remarks section of this document 中所见的行为是另一个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2014-05-15
    • 2014-02-04
    • 2011-05-28
    相关资源
    最近更新 更多