如何使VB.NET的参数作为通用类型起作用? [英] How to make Parameters of VB.NET function as Generic type?

查看:75
本文介绍了如何使VB.NET的参数作为通用类型起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个VB.NET函数,如下所示,传递给该函数的参数"x"的类型为单".但是,我想编写该函数,以便它可以接受任何数字类型,例如'Single','Double'和'Integer'.我知道做到这一点的一种方法是用相同的名称编写3个函数,但这太麻烦了.有人可以提出任何想法吗?谢谢.

I have a VB.NET function as below, the parameter 'x' that is passed to the function is of Type 'Single'. However, I want to write the function so that it can accept any numeric type such as 'Single', 'Double' and 'Integer'. I know one way of doing that is to write 3 functions with the same names, but it would be so tedious. Can anyone suggest any idea? Thank you.

Public Function Square(x As Single) As Single
  Return x * x
End Function

推荐答案

尝试以下方法

Public Function Square(Of T)(ByVal x As Object) As T
    Dim b As Object = Val(x) * Val(x)
    Return CType(b, T)
End Function

您可以像这样使用上面的功能

You can use above function like this

Dim p As Integer = Square(Of Integer)(10)
Dim d As Double = Square(Of Double)(1.5)

这篇关于如何使VB.NET的参数作为通用类型起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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