简体   繁体   English

在C#类之间传递值时缺少对象值

[英]Missing object values while passing value between C# classes

I have this method in the static class "ObjectMapper": 我在静态类“ ObjectMapper”中有此方法:

在此处输入图片说明

As we can see, the method has an object "dataReader" with some items ([0]). 如我们所见,该方法具有一个带有某些项目([0])的对象“ dataReader”。 But... When I invoke this method: 但是...当我调用此方法时:

在此处输入图片说明

The passed parameter is losing this record. 传递的参数将丢失此记录。 Even changing the method "DataReaderToObjectList" from "public static" to "public", the value is losing this data. 即使将方法“ DataReaderToObjectList”从“ public static”更改为“ public”,该值也会丢失此数据。 When my object has two or more records, it is being passed, but "killing" the first record. 当我的对象具有两个或多个记录时,将通过该记录,但是会“杀死”第一个记录。 If I do it in the "classic" way, I can manipulate the dataReader correctly. 如果以“经典”方式进行操作,则可以正确操作dataReader。 But I need this method working, once it is used in several places in the application. 但是,一旦在应用程序中的多个地方使用了这种方法,我就需要这种方法起作用。

In SelectAll() you call .Read() 在SelectAll()中,您调用.Read()
Boom first record gone 动臂第一记录消失了
You do NOTHING with that record 你什么都不用

In DataReaderToObject 在DataReaderToObject中
You call .Read() 您调用.Read()
Boom you are on the second record 繁荣,您处于第二纪录

Note that you can only enumerate the contents of an SqlDataReader object one time. 请注意,您一次只能枚举SqlDataReader对象的内容。 This includes enumerating them in the Results View preview window. 这包括在“ Results View预览窗口中枚举它们。 The data is being lost in this specific instance because you are enumerating them in the debugger, which exhausts the reader, then stepping into the function with an exhausted reader 数据在此特定实例中丢失,因为您是在调试器中枚举数据,从而耗尽了读取器,然后使用了疲惫的读取器进入了函数

I think there is also a more fundamental error in your code. 我认为您的代码中还有一个更基本的错误。 You are calling the Read method twice on the same instance without actually enumerating any of the data that resulted from the first read. 您在同一实例上两次调用Read方法,而没有实际枚举第一次读取产生的任何数据。 You can fix this by removing the Read call in the SelectAll method 您可以通过在SelectAll方法中删除Read调用来解决此问题。

I found an alternative solution for this problem, that solved (at least for now): 我找到了解决该问题的替代解决方案,至少已经解决了:

In the item 1, I declared a generic object that gets the attributes and values from dataReader and passed as a parameter (doing an explicit cast, as we can see) to a new method that gets this object as SqlDataReader, as shown in item 2 of image below. 在第1项中,我声明了一个通用对象,该对象从dataReader获取属性和值,并作为参数(如我们所见,进行显式转换)传递给一个新方法,该方法将该对象作为SqlDataReader进行获取,如第2项所示下图。

在此处输入图片说明

This new method is placed in the same static class ObjectMapper, but oddly I'm being able to pass my object as parameter without losing any data. 这个新方法放置在同一静态类ObjectMapper中,但是奇怪的是,我能够将我的对象作为参数传递而不会丢失任何数据。 @Blam, your theory makes sense, but didn't worked here in this case. @Blam,您的理论是有道理的,但在这种情况下没有用到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM