VB.NET - 类中的扩展函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17756646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET - Extension functions within a class?
提问by Lou
I'm trying to make a Class library with a function to convert binary integers to denary, and vice versa, so that I can import it into another project without having to rewrite the function. It works fine, here's part of the class:
我正在尝试创建一个带有函数的类库,可以将二进制整数转换为 denary,反之亦然,这样我就可以将它导入到另一个项目中,而无需重写该函数。它工作正常,这是课程的一部分:
Public Class BinaryDenary
Public Shared Function ToBinary(ByVal DenaryNumber As Integer) As Integer
Dim Binary As String = ""
While DenaryNumber > 0
If DenaryNumber Mod 2 = 1 Then
Binary = 1 & Binary
Else
Binary = 0 & Binary
End If
DenaryNumber \= 2
End While
Return CInt(Binary)
End Function
End Class
I've tested it within the project and it works fine.
我已经在项目中对其进行了测试,并且运行良好。
ToBinary(3) 'Returns 11
ToDenary(110) 'Returns 6
But - mostly for aesthetic reasons - I'd like to be able to use it like an extension method, so that I can take a variable and do this:
但是 - 主要是出于美学原因 - 我希望能够像扩展方法一样使用它,以便我可以使用一个变量并执行以下操作:
NormalInt.ToBinary(3)
But I can't write extension methods inside of a class. Is there any way of doing this? It's not hugely important, but I like to use extension methods where I can.
但是我不能在类中编写扩展方法。有没有办法做到这一点?这不是很重要,但我喜欢尽可能使用扩展方法。
回答by Zach dev
An extension method written in VB .NET, must be in a Moduleand be marked with the Extensionattribute, something like this:
用 VB .NET 编写的扩展方法,必须在 a 中Module并用Extension属性标记,如下所示:
Public Module BinaryDenary
<Extension()>
Function ToBinary(ByVal DenaryNumber As Integer) As Integer
Dim Binary As String = ""
While DenaryNumber > 0
If DenaryNumber Mod 2 = 1 Then
Binary = 1 & Binary
Else
Binary = 0 & Binary
End If
DenaryNumber \= 2
End While
Return CInt(Binary)
End Function
End Module
If the module isn't in the same namespace, you should import the namespace where it is used.
如果模块不在同一个命名空间中,您应该在使用它的地方导入命名空间。

