简体   繁体   English

使用F#代码中的C#中定义的扩展方法

[英]Using extension methods defined in C# from F# code

I have a series of extension methods defined for various classes in a C# library. 我为C#库中的各种类定义了一系列扩展方法。 I'm currently writing some F# code and instead of rewriting that code I would simply like to use my existing extension methods in my F# code. 我正在编写一些F#代码,而不是重写代码,我只想在我的F#代码中使用现有的扩展方法。

I have added a reference to the library and used the open statement to import the namespace, but the extension methods to not appear in F# 我添加了对库的引用并使用open语句导入命名空间,但扩展方法没有出现在F#中

Update: 更新:

In the current version of F#, you can simply consume extension methods by adding 在当前版本的F#中,您可以通过添加来简单地使用扩展方法

open TheNamespaceOfExtensionMethod

to your source file (just like you do in C# with a using directive) and simply call the extension method as if it was a normal instance method. 到您的源文件(就像您在C#中使用using指令一样)并简单地调用扩展方法,就像它是一个普通的实例方法一样。

By the way, you can always call them directly just like a normal static method and pass the object reference as the first parameter without any directives if you want. 顺便说一句,您可以像普通的静态方法一样直接调用它们,并将对象引用作为第一个参数传递,如果需要,不带任何指令。 An extension method is simply a static method decorated with ExtensionAttribute under the hood. 扩展方法只是一个在引擎盖下使用ExtensionAttribute修饰的静态方法。

Original answer (before F# 2010 beta; not true anymore, as Dykam points out): 原始答案(在F#2010测试版之前;不再是真实的,正如Dykam指出的那样):

I don't think extension methods are supported by F#. 我不认为F#支持扩展方法。 You can always call them directly just like a normal static method and pass the object reference as the first parameter. 您可以像普通静态方法一样直接调用它们,并将对象引用作为第一个参数传递。

Being able to 'import' C#/VB extension methods will be supported in the next release of F#. 下一版本的F#将支持能够“导入”C#/ VB扩展方法。

See also 也可以看看

F# extension methods in C# C#中的F#扩展方法

for more detail on the topic. 有关该主题的更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM