Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

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

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

Example:

<Extension>
Public Function MyExtension(value As Object) As Object
    Return value
End Function

The above functions won't work for object instance:

Dim myObj1 As New Object()
Dim myObj2 = myObj1.MyExtension()

The compiler does not accept it, is the problem in my computer? :)

UPDATE
The problem seems to occur only in VB, where members of object are looked-up by reflection (late-bound).

UPDATE AFTER ANSWERED
FYI, as vb has an advantage that C# lacks that is, members of imported Modules are imported to the global scope so you can still use this functions without their wrapper:

Dim myObj2 = MyExtension(myObj1)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It seems like not supporting Extension methods on Object was a design decision in VB.

As a result, the only way we could prevent extension methods from completely breaking existing late bound code was to prevent them from being used on anything typed as object.

http://blogs.msdn.com/b/vbteam/archive/2007/01/24/extension-methods-and-late-binding-extension-methods-part-4.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...