在C#F#扩展方法 [英] F# extension methods in C#
本文介绍了在C#F#扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果你定义一些扩展方法,性质写在F#组装,然后使用该程序集在C#中,你会看到定义的扩展在C#?
如果是这样,这将是太酷了。
解决方案
[< System.Runtime.CompilerServices.Extension>]
模块方法=
并[d System.Runtime.CompilerServices.Extension]的计算值
让存在(OPT:字符串选项)=
匹配与选择
|有些_ - >真正
|无 - >假
这个方法可以在C#仅通过加入(使用使用)的命名空间在那里将要使用的文件中使用。
如果(p2.Description.Exists()){...}
在评论扩展静态方法回答问题:
命名空间ExtensionFSharp模块CollectionExtensions = 键入System.Linq.Enumerable与
静态成员RangeChar(第一:字符,最后:字符)=
{第一..最后}
在F#你怎么称呼它,像这样:
开放System.Linq的
开放ExtensionFSharp.CollectionExtensions让rangeChar = Enumerable.RangeChar('A','Z')
printfn包含%i个项目rangeChar.CountItems
在C#中你怎么称呼它,像这样:
使用系统;
使用System.Collections.Generic;
使用ExtensionFSharp; 类节目
{
静态无效的主要(字串[] args)
{
VaR方法= typeof运算(CollectionExtensions).GetMethod(Enumerable.RangeChar.2.static);
VAR rangeChar =(IEnumerable的<焦炭>)method.Invoke(空,新的对象[] {'A','Z'});
的foreach(在rangeChar变种C)
{
Console.WriteLine(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
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()) { ...}
Here is a link to the original blogpost.
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}
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
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屋!
查看全文