You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Boo语言脚本报错求助:读取Excel并序列化Item对象至XML失败

解决Boo脚本中访问非静态成员的错误

首先咱们先拆解你遇到的错误:

BCE0020: Boo.Lang.Compiler.CompilerError: An instance of type 'Mss.Item' is required to access non static member 'Id'.

这个报错的核心很清晰:你在代码末尾直接用Item.Id试图访问实例属性,但Item是类本身,不是具体的对象实例;同时调用serialize_row(Item, Item.Id)时,第一个参数传的是类而非实例,这就触发了编译器的类型检查错误。

接下来咱们一步步修正你的代码:

1. 调整序列化逻辑的调用时机

你需要在读取到每个Item实例的时候执行序列化,而不是在流程末尾直接调用。比如可以在读取数据的循环里嵌入序列化操作。

2. 修正后的完整代码

关键修改点我用注释标注出来了:

public class Item (IIDataReaderLoadable):
    Sequence as long
    Code as string
    Description as string
    Weight as decimal
    Id as Guid

    def LoadFromReader(reader as IDataReader):
        Sequence = long.Parse(reader[0].ToString())
        Code = reader[1].ToString()
        Weight = decimal.Parse(reader[2].ToString())
        Description = reader[3].ToString()
        Id = Guid.Parse(reader[4].ToString())

    TableName as string:
        get:
            return "Hoja1$"

operation read_MasterData_etlexcel:
    log = ProcessContext.GetLogger()
    file = ProcessContext.InputFile
    log.Info("Reading $file")
    for Data in EntityReader[of Item].Read(file):
        # 在这里调用序列化,传入当前的Item实例和它的Id
        serialize_row(Data, Data.Id)
        yield Row.FromObject(Data)

operation print_etlexcel:
    log = ProcessContext.GetLogger()
    for row in rows:
        log.Info(row.ToString())
        yield row

def serialize_row(it as Item, id as Guid):  # 把参数类型从Object改为Item,类型更严谨
    serializer = XmlSerializer(typeof(Item))
    writer = FileStream("output" + id.ToString() +".xml", FileMode.Create)
    try:  # 加try/finally确保文件流被正确关闭,避免资源泄漏
        serializer.Serialize(writer, it)
    finally:
        writer.Close()

# 删掉原来错误的serialize_row调用,现在已经在读取数据时触发序列化了

process process_owners_etlexcel:
    read_MasterData_etlexcel()
    print_etlexcel()

关键修改说明

  • 移除错误的全局调用:原来的serialize_row(Item, Item.Id)直接传入类Item和类的Id属性,这是错误的——Id是每个Item实例独有的属性,不是类的静态属性。
  • 在数据读取循环中执行序列化:遍历EntityReader返回的每个Data(也就是Item实例)时,传入该实例和它的Id到序列化函数,确保使用的是正确的对象实例。
  • 优化参数类型与资源管理:把序列化函数的参数类型从Object改为Item,让类型更明确;增加try/finally块确保文件流在操作完成后被关闭,避免资源泄漏。

这样修改后,脚本应该就能正常读取Excel数据、生成Item实例,并将每个实例单独序列化为XML文件了。

内容的提问来源于stack exchange,提问作者Maria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:39:59