Applying Extension method to generic class with generic type

老子叫甜甜 提交于 2019-12-04 11:21:58

问题


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



来源:https://stackoverflow.com/questions/349064/applying-extension-method-to-generic-class-with-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!