如何使一个类实例接受参数? [英] How to make a class-instance accept parameters?

查看:197
本文介绍了如何使一个类实例接受参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以使类实例接受参数并根据此参数生成结果。

I wonder if there is a way to make a class instance that accepts parameters and generate results according to this parameter.

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

This is very common in VB.net built-in classes, but I wonder how to make it myself

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

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

In the above code myNumber is a class which accepts some numbers and return the max.

推荐答案

您可以使用 默认属性 即可实现。如果您不希望它可以设置-可以将其标记为 ReadOnly ,如果您不想返回特定的值只返回没什么

You can use Default properties in order to achieve that. If you don't want it to be Set-able you can just mark it as ReadOnly, and if you don't want to return a specific value just return 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")

这样做的唯一缺点是您必须对返回的值进行某些操作(例如,将其分配给变量)。简单地做:

The only backside with this is that you must do something with the returned value (for instance assign it to a variable). Simply doing:

myNumbers(64, "Hello World!")

不起作用。

这篇关于如何使一个类实例接受参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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