嗨,我在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
有人可以帮助我识别此错误吗?任何帮助,将不胜感激。谢谢。
答案 0 :(得分:1)
您正在将此对象强制转换为GenericRecord ((GenericRecord)response.Message.Value["Product"])
,但它会将此((GenericRecord)response.Message.Value["Product"])["FamilyTree"]
作为对象返回。您需要将每个级别强制转换为GenericRecord才能获取其属性。
((GenericRecord)((GenericRecord)((GenericRecord)response.Message.Value["Product"])["FamilyTree"])["Class"])["Code"]