为每个方法调用实例化类 [英] instantiating class for each method call

查看:74
本文介绍了为每个方法调用实例化类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
我是.NET编程和OOP的新手.
我在vb.net中有以下代码.我在DbUtilities类中有3个方法,分别是GetLastRptDate()ClearTable()UpdateLastRptDate().如您所知,我实例化了类DBUtilities一次,并调用了3个实例方法

Hello,
I''m new to .NET programming and OOP.
I have the following code in vb.net. I have 3 methods in DbUtilities class, namely GetLastRptDate(), ClearTable(), and UpdateLastRptDate(). As you can I instantiated the class, DBUtilities once and called the 3 instance methods

DB.GetLastRptDate()<br />
DB.ClearTable("Delete_ReportData")<br />
DB.UpdateLastRptDate(dt)


我的问题是:首先,只要在添加,删除,选择,更新记录方面与一个数据库表相关,将多个方法放在一个类中是否很好?
第二个问题,我是否只需要在开始时实例化对象/类DbUtilities,然后在该类中调用几个方法?不知道是否必须为该类中调用的每个方法创建该类的新实例.


My questions are: First, is it good to place multiple methods in a single class as long as it pertains to one database table in terms of adding, deleting, selecting, updating records?
Second question, do I need to instantiate the object/class DbUtilities ONLY ONCE at the beginning then call several methods in the class after that? Not sure if I have to create a new instance of this class for every method that is called in the class.

Private Sub BuildPreviousDayData()
        ''Get Last Report Date
        Dim DB As New DbUtilities(conn)
        Dim lastRptDateDet As ReportDateDetails = DB.GetLastRptDate()
        Dim frDate As DateTime
        If lastRptDateDet Is Nothing Then
            frDate = dt ''Default to current Date
        Else
            frDate = lastRptDateDet.LastRptDate
        End If
        If frDate <> dt Then
            ''deletes ReportData and LastRunDAte Tables
           DB.ClearTable("Delete_ReportData")
            ''updates Report Date Table with current date
           DB.UpdateLastRptDate(dt)
        End If
    End Sub


非常感谢!


感谢您的所有回复.但是,我仍然不清楚第二个问题.
Abhinav和Nithin都说过,一个类的每个实例都有自己的数据副本.

我不确定在类DbUtilities中这些方法与它们之间的关系(如下所示),每种方法都会打开一个新的SQL连接和sql命令实例.

如果我一开始只实例化DbUtilities类,则随后调用这3个方法,下面给出的代码对这种方法有何影响?请澄清.


Thank you very much!


Thanks for all your responses. However, I am still not clear with my second question.
Abhinav and Nithin have both said that each instance of a class has its own copy of data associated with it.

I am not sure how that correlates with these methods in my class DbUtilities (as shown below), each method opens up a new instance of SQL connection and sql command.

If I only instantiate the class DbUtilities once in the begining, then calling the 3 methods subsequently, What is wrong with this approach given my code below? Please clarify.

Public Class DbUtilities
         Private connectionString As String
         Public Sub New(ByVal connection As String)
            connectionString = ConfigurationManager.ConnectionStrings( _
                  connection).ConnectionString
         End Sub
         Public Sub ClearTable(ByVal storedProc As String)
                  Dim conn As New SqlConnection(connectionString)
                  Dim cmd As New SqlCommand(storedProc, conn)
                  cmd.CommandType = CommandType.StoredProcedure
                  Try
                     conn.Open()
                     cmd.ExecuteNonQuery()
                  Catch ex As Exception
                  Finally
                     conn.Close()
                  End Try
         End Sub
         Public Function GetLastRptDate() As ReportDateDetails
         Dim conn As New SqlConnection(connectionString)
         Dim reader As SqlDataReader
         Dim cmd As New SqlCommand(&quot;Select_LastRptDate&quot;, conn)
         cmd.CommandType = CommandType.StoredProcedure
         Try
                  conn.Open()
                  reader = cmd.ExecuteReader(CommandBehavior.SingleRow)
                  If (reader.HasRows) Then
                           reader.Read()
                           Dim lastRptDtls As ReportDateDetails = New ReportDateDetails( _
                                       reader(&quot;ReportDate&quot;).ToString())
                           reader.Close()
                           Return lastRptDtls
                  End If
                  reader.Close()
                  Return Nothing
         Catch ex As Exception
                  Return Nothing
         Finally
                  conn.Close()
         End Try
         End Function
         Public Sub UpdateLastRptDate(ByVal dt As DateTime)
                  Dim conn As New SqlConnection(connectionString)
                  Dim cmd As New SqlCommand(&quot;Update_ReportDate&quot;, conn)
                  cmd.CommandType = CommandType.StoredProcedure
                  cmd.Parameters.AddWithValue(&quot;@ReportDate&quot;, dt)
                  Try
                           conn.Open()
                           cmd.ExecuteNonQuery()
                           Catch ex As Exception
                  Finally
                           conn.Close()
                  End Try
         End Sub
End Class



非常感谢您的所有投入!



Thank you so much for all your inputs!

推荐答案

每个实例都会附带其on数据(和属性).
要单独处理这些数据,您需要单独的实例.

但是,如果您的类只是一个帮助器类,即提供了其他类使用的一些方法,则一个实例就足够了.

希望这对您有帮助!
Every instance will come with its on data (and attributes).
To do processing on this data individually, you need separate instances.

However, if your class is just a helper class i.e. provides some methods that other classes use, one instance is enough.

Hope this helps!


将所有相关方法归为一个类是很好的方法.

如果只需要创建一个对象,则应实施Singleton模式
It is fine to group all related methods in a single class.

If you need to create an object only once then you should implment the Singleton Pattern


将所有方法以有意义的方式进行分组实际上是一种好习惯.例如,您可能有一个名为DatabaseManipulator的类,该类包含诸如InsertMyRecord,DeleteMyRecord,UpdateMyrecord等方法.当您以完全不需要注释的方式进行命名和分组时,方法的数量无关紧要.

同样,一个类的每个实例都具有它自己与之关联的数据的副本.因此,如果您想在整个类中的Object1中使用某些东西,那么将对该对象的引用传递给您需要从中访问该对象的函数会更好.

希望这对您有所帮助. :)
It''s actually good practice to group all methods in a meaningful manner. For example, you may have a class called DatabaseManipulator which comprises of methods such as InsertMyRecord, DeleteMyRecord, UpdateMyrecord and so on. The number of methods will not matter much when you have named and grouped in such a way that comments aren''t required at all.

Also, each instance of a class has it''s own copy of the data associated with it. So if you''re someone who wants to use something in Object1 throughout the class, then it would be more better to pass a reference of that object to the function from which you need to access that object.

Hope this helped. :)


这篇关于为每个方法调用实例化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆