检索数据 LINQ 与反射
我希望有人能告诉我哪种方法是检索某些数据的更有效和/或更正确的方法。
我有一些来自第 3 方的 XML 文件及其附加的 DTD。因此,我已将 DTD 转换为 C# 类,以便可以将 XML 反序列化为类。我现在需要映射该数据以匹配我的数据结构的设置方式。
最终的问题是;我应该使用反射还是 LINQ。 XML 的格式在设计上有些通用,其中的内容保存在 Items [Array] 或 Item [Object] 中。
我已经完成了以下操作:
TheirClass class = theirMessage.Items.Where(n=> n.GetType() == typeof(TheirClass)).First() as TheirClass;
MyObject.Param1 = ConversionHelperClass.Convert(class.Obj1);
MyObject.Param2 = ConversionHelperClass.Convert(class.Obj2);
我还可以使用反射做一些事情,其中我传递我想要获取的类和属性的名称。
在这里尝试以正确的方式做事。
I was hoping someone could tell me which is the more efficient and/or correct way to retrieve some data.
I have some XML files coming from a 3rd party and their attached DTDs. So I've converted the DTD into a C# Class so I can deserialize the XML into the classes. I now need to map that data to match the way my data structures are set up.
The question ultimately is; should I use reflection or LINQ. The format of the XML is somewhat generic by design, where things are held in Items [Array] or Item [Object].
I've done the following:
TheirClass class = theirMessage.Items.Where(n=> n.GetType() == typeof(TheirClass)).First() as TheirClass;
MyObject.Param1 = ConversionHelperClass.Convert(class.Obj1);
MyObject.Param2 = ConversionHelperClass.Convert(class.Obj2);
I can also do some stuff with Reflection where I pass in the names of the Classes and Attributes I'm trying to snag.
Trying to do things the right way here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为一般规则,我建议避免反思,除非绝对必要!它引入了性能开销,并且意味着您错过了编译器团队努力为我们提供的所有可爱的编译时检查。
Linq toEntity 本质上是针对内存中的数据集进行查询,因此速度非常快。
如果您的最终目标是解析 xml 文档中的信息,我建议您查看 XDocument 类。它为查询 xml 文档提供了一个非常好的抽象。
As a general rule I'd suggest avoiding reflection unless it is absolutely necessary! It introduces a performance overhead AND means that you miss out on all of the lovely compile time checks that the compiler team have worked so hard to give us.
Linq to entities essentially queries against an in memory data set, so it can be very fast.
If your ultimate goal is to parse information from an xml document, I'd suggest checking out the XDocument class. It provides a very nice abstraction for querying xml documents.