Can you make an Extension Method Static/Shared?

跟風遠走 提交于 2019-12-01 15:57:40

问题


OK, I've probably misunderstood something here but, as far as I can see ...

  • An extension method has to be contained in a module, not a class
  • You can't make methods in modules Static/Shared
  • Therefore you can't use an extension method on a class without instantiating it.

In other words you can't make an extension method on String called "MyExtensionMethod" and use:

String.MyExtensionMethod("String")

But instead ..

Dim test As String
test.MyExtensionMethod("string")

Is this correct? Or is there a way I can get extension methods to work as static methods?


回答1:


You are correct. Extension methods can only act on instances of a type.

And no, unfortunately there's no crafty way to write extension methods that act on the types themselves, behaving like static methods.



来源:https://stackoverflow.com/questions/2880773/can-you-make-an-extension-method-static-shared

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