你能扩展方法静态/共享?你能、静态、方法

2023-09-03 05:02:00 作者:空

OK,我可能误解了一些东西,但是,据我可以看到... ...

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

延伸方法,已被包含在一个模块,而不是一个类 您不能让方法模块静态/共享 因此,你不能没有实例化它使用一个类的扩展方法。

在换句话说,你不能对字符串扩展方法被称为MyExtensionMethod和使用:

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?

推荐答案

您是正确的。扩展方法只能作用于一个类型的实例。

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.