要在vb.net中编写扩展方法,必须将它们放在Module中,模块中定义的所有方法都会添加到全局命名空间中。
有没有办法从全局命名空间中删除这些方法,因此它们只用作扩展方法,或者实际上是否先写入模块名称?
示例
TypeExtensionMethods.vb:
Imports System.Runtime.CompilerServices
Public Module TypeExtensionMethods
Private ReadOnly numericTypes As TypeCode() = {
TypeCode.Byte, TypeCode.SByte, TypeCode.UInt16,
TypeCode.UInt32, TypeCode.UInt64, TypeCode.Int16,
TypeCode.Int32, TypeCode.Int64, TypeCode.Decimal,
TypeCode.Double, TypeCode.Single}
<Extension()>
Public Function IsNumber(type As Type) As Boolean
Dim currentTypeCode As TypeCode = Type.GetTypeCode(type)
Return currentTypeCode.IsNumber()
End Function
<Extension()>
Public Function IsNumber(type As TypeCode) As Boolean
Return numericTypes.Any(Function(tc) tc = type)
End Function
End Module
Class1.vb:
Class Class1
Sub Main(value as Object)
'This should work
dim result1 as Boolean = value.GetType().IsNumber()
'This should work
dim result2 as Boolean = TypeExtensionMethods.IsNumber(value.GetType())
'This should not work, the method IsNumber is polluting as it can be called without specifying where its defined.
dim result3 as Boolean = IsNumber(value.GetType())
End Sub
End Class
答案 0 :(得分:0)
似乎这是不可能的!