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

后端 未结 6 1049
南方客
南方客 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:04

    See this question I asked some time ago. Basically, you can extend Object in VB.NET if you want; but for backwards compatibility reasons, no variable declared as Object will be able to use your extension method. This is because VB.NET supports late binding on Object, so an attempt to access an extension method will be ignored in favor of trying to find a method of the same name from the type of the object in question.

    So take this extension method, for example:

    
    Public Sub Dump(ByVal obj As Object)
        Console.WriteLine(obj)
    End Sub
    

    This extension method could be used here:

    ' Note: here we are calling the Dump extension method on a variable '
    ' typed as String, which works because String (like all classes) '
    ' inherits from Object. '
    Dim str As String = "Hello!"
    str.Dump()
    

    But not here:

    ' Here we attempt to call Dump on a variable typed as Object; but '
    ' this will not work since late binding is a feature that came before '
    ' extension methods. '
    Dim obj As New Object
    obj.Dump()
    

    Ask yourself why extension methods don't work on dynamic variables in C#, and you'll realize the explanation is the same.

提交回复
热议问题