试图让一个类返回一个字符串

时间:2012-05-18 20:50:48

标签: vb.net

我正在将代码从代码隐藏转移到类并遇到问题。我有一个方法,使一个字符串(一个HTML发票)。在该方法中,创建最终金额。我想创建一个名为Invoice的类,它将使用方法“CreateInvoice”,它将返回一个字符串,我还想设置该对象的finalCharge属性。我完成了所有繁重的工作,但正在设置课程是我遇到麻烦的部分

Public Class Invoice
    Public finalCharge As Double
    Public invoiceString As String
    Public billingId As Integer
    Public clientID As Integer

Public Shared Function CreateInvoice(ByVal bill_id As Integer, ByVal client_id As Integer) As String
    ... 'create string invoice
    ... 'tally final charge
End Function


'On my code-behind page.
dim y as string
dim x as Invoice

y = x.CreateInvoice(1225,8855) <-- this line doesn't work.

感谢您帮忙整理出来!

1 个答案:

答案 0 :(得分:2)

这是一个Shared函数 - 这意味着您不需要(或想要)该类的实例来使用它。你应该这样称呼:

Invoice.CreateInvoice(1225, 8855)

那就是说,我不完全确定它应该Shared开头,因为你也说:

  

[我] ...想要设置finalCharge属性

由于Shared函数只能访问Shared属性(因为没有实例),您可能确实希望它是实例函数:

Public Class Invoice
    Public finalCharge As Double
    Public invoiceString As String
    Public billingId As Integer
    Public clientID As Integer

    Public Function CreateInvoice(ByVal bill_id As Integer, ByVal client_id As Integer) As String
        ... 'create string invoice
        Me.finalCharge = ... 'tally final charge
    End Function
End Class

在这种情况下,你可以这样称呼:

Dim x as New Invoice()
Dim y as String = x.CreateInvoice(1225, 8855)
Dim finalCharge as Double = x.finalCharge