C# 中的 F# 扩展方法 [英] F# extension methods in C#
本文介绍了C# 中的 F# 扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果您在用 F# 编写的程序集中定义一些扩展方法、属性,然后在 C# 中使用该程序集,您会看到 C# 中定义的扩展吗?
If you were to define some extension methods, properties in an assembly written in F#, and then use that assembly in C#, would you see the defined extensions in C#?
如果是这样,那就太酷了.
If so, that would be so cool.
推荐答案
[<System.Runtime.CompilerServices.Extension>]
module Methods =
[<System.Runtime.CompilerServices.Extension>]
let Exists(opt : string option) =
match opt with
| Some _ -> true
| None -> false
此方法只能通过将命名空间(使用 using)添加到将要使用的文件中来在 C# 中使用.
This method could be used in C# only by adding the namespace (using using) to the file where it will be used.
if (p2.Description.Exists()) { ...}
在扩展静态方法"评论中回答问题:
Answering question in comments "Extension Static Methods":
namespace ExtensionFSharp
module CollectionExtensions =
type System.Linq.Enumerable with
static member RangeChar(first:char, last:char) =
{first .. last}
在 F# 中,您可以这样称呼它:
In F# you call it like so:
open System.Linq
open ExtensionFSharp.CollectionExtensions
let rangeChar = Enumerable.RangeChar('a', 'z')
printfn "Contains %i items" rangeChar.CountItems
在 C# 中,您可以这样称呼它:
In C# you call it like so:
using System;
using System.Collections.Generic;
using ExtensionFSharp;
class Program
{
static void Main(string[] args)
{
var method = typeof (CollectionExtensions).GetMethod("Enumerable.RangeChar.2.static");
var rangeChar = (IEnumerable<char>) method.Invoke(null, new object[] {'a', 'z'});
foreach (var c in rangeChar)
{
Console.WriteLine(c);
}
}
}
现在,把我那该死的奖章给我!
Now, give me my freaking medal!
这篇关于C# 中的 F# 扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文