在C#中用Unit返回类型实现F#接口成员

Aka*_*ash 4 null f# unit-type

假设我在F#中定义了以下接口:

type IFoo<'T> = 
  abstract member DoStuff : 'T -> unit
Run Code Online (Sandbox Code Playgroud)

如果我在C#中实现这一点,则需要方法签名为:

public void DoStuff<T>(T arg) {...}
Run Code Online (Sandbox Code Playgroud)

我真正想做的是引用FSharp.Core,然后使用:

public Unit DoStuff<T>(T arg) {...}
Run Code Online (Sandbox Code Playgroud)

这将简化其他代码,因为我不必处理Action vs Func。我猜测没有任何干净的方法可以实现这一目标?邪恶的骇客怎么样?

Dan*_*iel 5

Unitto的转换void烘焙到编译器中。FuncConvertF#Core中有一个用于在FSharpFunc和之间进行转换的类Converter。定义要转换Action<T>为的相似类Func<T, Unit>怎么办?

static class ActionConvert {
    private static readonly Unit Unit = MakeUnit();

    public static Func<T, Unit> ToFunc<T>(Action<T> action) {
        return new Func<T, Unit>(x => { action(x); return Unit; });
    }

    private static Unit MakeUnit() {
        //using reflection because ctor is internal
        return (Unit)Activator.CreateInstance(typeof(Unit), true);
    }
}
Run Code Online (Sandbox Code Playgroud)

那你可以做

var foo = new Foo<int>();
var func = ActionConvert.ToFunc<int>(foo.DoStuff);
Run Code Online (Sandbox Code Playgroud)

您甚至可以放弃该Unit实例,然后返回null