VB.Net 在不污染全局命名空间的情况下制作扩展方法?
VB.Net making extension method without polluting global namespace?
要在 vb.net 中编写扩展方法,您必须将它们放在模块中,模块中定义的所有方法都会添加到全局命名空间。
有没有办法从全局命名空间中删除这些方法,以便它们仅用作扩展方法,或者如果您实际上先写模块名称?
例子
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
看来这不可能!
要在 vb.net 中编写扩展方法,您必须将它们放在模块中,模块中定义的所有方法都会添加到全局命名空间。
有没有办法从全局命名空间中删除这些方法,以便它们仅用作扩展方法,或者如果您实际上先写模块名称?
例子
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
看来这不可能!