为何无法通过RTTI获取Spring.Collections中IList<T>的Add与Clear方法?
问题:MVCFramework反序列化Spring.Collections.IList接口失败
尝试使用MVCFramework反序列化Spring.Collections中的IList<T>接口时操作失败,原因是序列化逻辑中的IsWrap()函数会校验目标对象是否存在Add()和Clear()方法,但IList<T>的RTTI信息中并未包含这两个方法。
TList<TPerson>和TObjectList<TPerson>均可正常完成反序列化,只有IList<TPerson>无法正常工作。
相关代码示例
TPerson = class (TInterfacedObject) private fLastName: String; fFirstName: String; public property FirstName: String read fFirstName write fFirstName; property LastName: String read fLastName write fLastName; end; implementation uses Generics.Collections, Spring.Collections, MVCFramework.Serializer.Intf, MVCFramework.Serializer.JsonDataObjects; procedure TSerializerTest.JsonToCollection; begin var strJson: string := '[{"FirstName": "Ricardo", "LastName": "The killer" }, {"FirstName": "Zorro", "LastName": "Z-Man" }]'; var oPersons : IList<TPerson> := TCollections.CreateObjectList<TPerson> ; // var oPersons : TList<TPerson> := TList<TPerson>.Create ; // var oPersons : TObjectList<TPerson> := TObjectList<TPerson>.Create() ; var lSerializer: IMVCSerializer := TMVCJsonDataObjectsSerializer.Create; lSerializer.DeserializeCollection(strJson, oPersons, TPerson); Assert.AreEqual(oPersons[0].FirstName , 'Ricardo'); Assert.AreEqual(oPersons[1].FirstName , 'Zorro'); end;
RTTI验证代码
procedure TSerializerTest.CheckAddAndClearRTTI; var ObjectType: TRttiType; FContext: TRttiContext; begin var oPersons : IList<TPerson> := TCollections.CreateObjectList<TPerson> ; // 确认Add和Clear方法实际存在 oPersons.Add(TPerson.Create); oPersons.Clear; ObjectType := FContext.GetType(oPersons.AsObject.ClassInfo); if (ObjectType.GetMethod('Add') <> nil) and (ObjectType.GetMethod('Clear') <> nil) then begin ShowMessage('Is List'); // 不会执行到这里,原因是什么? end; end;
内容的提问来源于stack exchange,提问作者Ravaut123
相关产品推荐
相关产品推荐

