【问题标题】:Unable to cast Generic record to object无法将通用记录转换为对象
【发布时间】:2019-11-23 23:48:49
【问题描述】:

您好,我在 c# 中有以下模型。这些是 Avro 文件。

public ProductMessageEvents GetValue(TestPayload parameter)
{
    return new ProductMessageEvents()
        {
            Metadata = new KafkaProductEvent.Metadata
                {
                    Timestamp = "test",
                    Environment = "test"
                },
            Product = new KafkaProductEvent.Product
                {
                    AgeGrading = "test",
                    KeycodeType = "type1",
                    FamilyTree = new KafkaProductEvent.FamilyTree
                        {
                            Class = new KafkaProductEvent.CodeNamePair
                                {
                                    Code = "test code",
                                    Name = "test name"
                                }
                        },
                    DssProduct = new KafkaProductEvent.DssProduct
                        {
                            DocumentStatus = "active"
                        }
                      Options = new Option[]
            {
              new Option
              {
                PrimaryColour = new CodeNamePair
                {
                  Name = "White",
                },
                SecondaryColour = new CodeNamePair
                {
                  Name = "red",
                }
              },
              new Option
              {
                PrimaryColour = new CodeNamePair
                {
                  Name = "White",
                }
              },
                },
            Version = "latestVersion"
        };
    }
}

如果我尝试访问以下值,它会起作用。

 object ageGrading = ((GenericRecord)response.Message.Value["Product"])["AgeGrading"];

如果我尝试访问以下值,则会抛出

object familyTree = ((GenericRecord)response.Message.Value["Product"])["FamilyTree"]["Class"]["Code"];

它抛出错误Cannot apply indexing with [] to an expression of type object

有人可以帮我找出这个错误吗?任何帮助,将不胜感激。谢谢。

【问题讨论】:

  • 嗨。它不工作。谢谢
  • 没有人读过异常消息 :( "Cannot apply indexing with [] to an expression of type object" 表示您正在尝试将 [] 索引应用于表达式对象类型

标签: c# apache-kafka avro confluent-platform


【解决方案1】:

您正在将此对象转换为 GenericRecord ((GenericRecord)response.Message.Value["Product"]),但它会将此 ((GenericRecord)response.Message.Value["Product"])["FamilyTree"] 作为对象返回。您需要将每个级别转换为 GenericRecord 以获取其属性。

((GenericRecord)((GenericRecord)((GenericRecord)response.Message.Value["Product"])["FamilyTree"])["Class"])["Code"]

【讨论】:

  • 我可以知道每个级别我该怎么做吗?
  • 嗨,如果我有一些可枚举的数据,那么我们如何获取数据?我在上面添加了一些代码。
  • 将其转换为 IEnumerable<Options>
  • 我已经厌倦了施法。我附上了屏幕截图。但是我怎样才能获得非公共成员?在非公开成员中,有一些内容具有我的价值。
  • 我真的很喜欢这个人的回答。 stackoverflow.com/questions/5816870/…。如果必须这样做,则需要使用反射,而这完全是另一回事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多