【问题标题】:How to make a class-instance accept parameters?如何使类实例接受参数?
【发布时间】:2017-03-07 14:29:29
【问题描述】:

不知道有没有办法制作一个接受参数的类实例,并根据这个参数生成结果。

这在VB.net内置类中很常见,但我想知道如何自己制作

Dim myNumbers as new NUMBERS
myNumbers.First = 1
myNumbers.Second = 2
Msgbox(myNumbers(1,2,3,4,5,5).max)

在上面的代码中,myNumber 是一个接受一些数字并返回最大值的类。

【问题讨论】:

  • 类不带参数,方法可以;那些看起来像属性。我们看不到NUMBERS,所以我们只能猜测出什么问题
  • 在您的示例中,FirstSecond 是类的属性,Max 是一个函数。阅读课程的这些方面。
  • 也许你说的是类构造函数有参数?

标签: vb.net class oop default


【解决方案1】:

您可以使用Default properties 来实现这一点。如果您不希望它是Set-able,您可以将其标记为ReadOnly,如果您不想返回特定值,只需返回Nothing

从属性中返回一些东西:

Default Public ReadOnly Property Calculate(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer) As Integer
    Get
        Dim d As Integer = a * b + c + Me.First
        DoSomeStuff(d)
        Return d * Me.Second
    End Get
End Property

什么都不返回:

Default Public ReadOnly Property Calculate(ByVal a As Integer, ByVal b As String) As Object
    Get
        Dim c As String = DoStuff()
        DoSomeOtherStuff(a, b, Me.First, Me.Second, c)
        Return Nothing
    End Get
End Property

用法示例:

'With return value.
Dim num As Integer = myNumbers(34, 5, 13)

'Ignoring return value.
Dim dummy As Object = myNumbers(64, "Hello World!")

'Ignoring return value.
Dim dummy As Object = myNumbers.Calculate(13, "I am text")

唯一的缺点是你必须对返回的值做一些事情(例如将它分配给一个变量)。简单地做:

myNumbers(64, "Hello World!")

没用。

【讨论】:

  • @DragonInCresent :很高兴我能帮上忙!祝你的项目好运!
猜你喜欢
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 2011-11-15
  • 1970-01-01
  • 2012-07-03
  • 1970-01-01
相关资源
最近更新 更多