VB.NET: impossible to use Extension method on System.Object instance

后端 未结 6 1047
南方客
南方客 2020-12-03 09:49

Can I make an Extension method for all the subclasses of System.Object (everything)?

Example:


Public Function MyExtens         


        
6条回答
  •  借酒劲吻你
    2020-12-03 10:18

    Sure you can, though you might want to be sparing about what you do here so as not to clutter every object. An extension method I like using for Object is a method called IsIn() that functions similarly to the SQL IN() statement. It's nice to say things like:

    If someString.IsIn("a", "b", "c") Then
       DoSomething()
    Else If someInt.IsIn(1, 2, 3) Then
       DoSomethingElse()
    Else If someObj.IsIn(1, "q", #7/1/2010#) Then
       DoSomethingTheThirdWay()
    End If
    

    EDIT -

    Added implementation of IsIn() extension method below to help commenter.

    Imports System.Runtime.CompilerServices
    
    Public Module ObjectExtensions
      
      Public Function IsIn(obj As Object, ParamArray values() As Object) As Boolean
        For Each val As Object In values
          If val.Equals(obj) Then Return True
        Next
        Return False
      End Function
    End Module
    

提交回复
热议问题