C# 函数返回类型
我有一个简单的函数,它根据以下内联SQL语句(简化版本)从数据库返回单列数据: 如果SQL返回一行,它可以是NULL或整数,或者SQL不返回任何内容 在代码的另一部分中,我有:C# 函数返回类型,c#,vb.net,C#,Vb.net,我有一个简单的函数,它根据以下内联SQL语句(简化版本)从数据库返回单列数据: 如果SQL返回一行,它可以是NULL或整数,或者SQL不返回任何内容 在代码的另一部分中,我有: Dim userId As Object = New Object userId = GetBillingGroupToInvoice(name) 这里可以使用对象作为返回类型吗。如果不是,我应该指定什么作为这个函数的返回类型?这是用VB编写的,但用C#编写的答案也可以 感谢如果SQL查询返回整数或空值,您可能希望函
Dim userId As Object = New Object
userId = GetBillingGroupToInvoice(name)
这里可以使用对象作为返回类型吗。如果不是,我应该指定什么作为这个函数的返回类型?这是用VB编写的,但用C#编写的答案也可以
感谢如果SQL查询返回整数或空值,您可能希望函数返回可为空的int(
int?
在C#)而不是object,以提高类型安全性。如果SQL查询返回整数或空值,您可能希望函数返回可为空的int(int?
在C#)而不是对象,以提高类型安全性。将返回类型(如果不是DBNull)从ExecuteScalar转换为整数。您可以返回可为null的int类型(C#中的int) 将返回类型(如果不是DBNull)从ExecuteScalar转换为整数。您可以返回可为null的int类型(C#中的int) 您应该指定整数
返回类型,而不是对象
Function GetId(ByVal name As String) As Integer
Dim sql As String = "Select Id From table where username=@name"
Dim retValue as Integer = -1
Using cmd As New SqlCommand
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.Parameters.Add("@name",SqlDbType.VarChar,30).Value=name
Dim result = cmd.ExecuteScalar()
if Not IsNothing(result) And Not IsDBNull(result) Then
retValue=CType(result,Integer)
End If
End Using
return retValue
End Function
您应该指定
整数
返回类型,而不是对象
Function GetId(ByVal name As String) As Integer
Dim sql As String = "Select Id From table where username=@name"
Dim retValue as Integer = -1
Using cmd As New SqlCommand
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.Parameters.Add("@name",SqlDbType.VarChar,30).Value=name
Dim result = cmd.ExecuteScalar()
if Not IsNothing(result) And Not IsDBNull(result) Then
retValue=CType(result,Integer)
End If
End Using
return retValue
End Function
当SQL server不返回任何内容或
DBNull
(如果您不想在未返回行和DBNull之间造成差异)时,您的函数可能应该返回一个,即返回Nothing
然后,您可以这样调用您的方法:
Dim userId = GetBillingGroupToInvoice(name)
If userId.HasValue Then
'Do something with userId.Value'
End If
当SQL server不返回任何内容或
DBNull
(如果您不想在未返回行和DBNull之间造成差异)时,您的函数可能应该返回一个,即返回Nothing
然后,您可以这样调用您的方法:
Dim userId = GetBillingGroupToInvoice(name)
If userId.HasValue Then
'Do something with userId.Value'
End If
谢谢,但是如果列为NULL,则从类型“DBNull”到类型“Integer”的转换无效。此错误。谢谢,但是如果列为NULL,则从类型“DBNull”到类型“Integer”的转换无效。这个错误。