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

使用Apache.Avro包生成跨多个Schema文件的C#类时,共享枚举引用解析失败求助

使用Apache.Avro包生成跨多个Schema文件的C#类时,共享枚举引用解析失败求助

嘿,我最近在使用Apache.Avro包从Avro Schema生成C#代码时遇到了个棘手的问题,想请教下各位大佬!

我目前的场景是:有多个独立的Avro Schema文件,它们需要共用一些通用的枚举定义,比如下面这个PlanetEnum。我原本打算在各个记录Schema里直接引用这个共享枚举,不用重复写定义,但现在引用总是解析失败。

先给大家看下我的Schema内容:

记录Schema(MyModel)

{
  "name": "MyModel",
  "namespace": "My.Model",
  "type": "record",
  "fields": [
    {
      "name": "Planet",
      "type": "My.Model.PlanetEnum"
    }
  ]
}

共享枚举Schema(PlanetEnum)

{
  "name": "PlanetEnum",
  "namespace": "My.Model",
  "type": "enum",
  "symbols": [
    "Earth",
    "Mars"
  ]
}

然后是我用来生成C#代码的逻辑:

var codeCompileUnit = new CodeGen
{
    Schemas =
    {
        /* 我试过把枚举的定义直接内联到这里,结果生成还是失败
        Schema.Parse("""
        {
          "name": "PlanetEnum",
          "namespace": "My.Model",
          "type": "enum",
          "symbols": [
            "Earth",
            "Mars"
          ]
        }
        """),
        */
        Schema.Parse(schemaText)
    },
}.GenerateCode();

var stringWriter = new StringWriter(new StringBuilder());
var provider = CodeDomProvider.CreateProvider("csharp");
provider.GenerateCodeFromCompileUnit(codeCompileUnit, stringWriter, new CodeGeneratorOptions());

var schemaCode = stringWriter.ToString();
return schemaCode;

运行后抛出的错误信息是:

Avro.SchemaParseException: Undefined name: My.Model.PlanetEnum at 'fields[0].type'
at Avro.Schema.ParseJson(JToken jtok, SchemaNames names, String encspace)
at Avro.RecordSchema.createField(JToken jfield, Int32 pos, SchemaNames names, String encspace)
at Avro.RecordSchema.NewInstance(Type type, JToken jtok, PropertyMap props, SchemaNames names, String encspace)
at Avro.NamedSchema.NewInstance(JObject jo, PropertyMap props, SchemaNames names, String encspace)
at Avro.Schema.ParseJson(JToken jtok, SchemaNames names, String encspace)
at Avro.Schema.Parse(String json, SchemaNames names, String encspace)
at Avro.Schema.Parse(String json)

我本来以为把共享的枚举Schema也加到CodeGen的Schemas集合里就能解决引用问题,但哪怕内联进去还是报同样的错误。有没有朋友知道问题出在哪?或者正确的跨Schema引用共享类型的方式应该是怎样的?

备注:内容来源于stack exchange,提问作者xandermonkey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 15:09:35