Applying Extension method to generic class with ge

2020-06-03 04:30发布

问题:

I was working with the generic class in vb.net.
And it seems extension method cannot be applied to generic class without specifying the type.

I have this generic class

Public Class MyGeneric(Of T)
    'Methods and properties go here 
    '
    '
End Class  

This is Ok

<Extension()> _
Public Sub DoSomething(ByVal myGenericDoubleObj As MyGen(Of Double))

End Sub  

This is NOT Ok(IDE gives me error T as not defined.)

<Extension()> _
Public Sub DoSomethingGeneric(ByVal myGenericObj As MyGen(Of T))

End Sub

Is this something to do with the static checking of the .Net.
Saying me "Something which may you try with doing with Type T is may not compatible and I will not allow you to do it."

P.S. All the this pain I have taken as Generic Class comes from another library, And used at many different places. I am little wary of inheriting and adding this method in my inherited generic class.

回答1:

If you make your extension method a generic method it should work

i.e DoSomething (Of T) () instread of just DoSomething()

<Extension()> _
Public Sub DoSomething(Of T)(ByVal myGenericObj As MyGeneric(Of T))
End Sub

Hope this helps