Implement F# interface member with Unit return type in C#

*爱你&永不变心* 提交于 2019-12-04 03:56:34

问题


Suppose I've defined the following interface in F#:

type IFoo<'T> = 
  abstract member DoStuff : 'T -> unit

If I implement this in C# I need the method signature to be:

public void DoStuff<T>(T arg) {...}

What I really want to do is reference FSharp.Core and then use:

public Unit DoStuff<T>(T arg) {...}

This would simplify other code because I wouldn't have to deal with Action vs Func. I'm guessing that there isn't any clean way to achieve this? How about some evil hacks?


回答1:


Transformation of Unit to void is baked into the compiler. There's a FuncConvert class in F# Core for converting between FSharpFunc and Converter. What about defining a similar class to convert Action<T> to 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);
    }
}

Then you could do

var foo = new Foo<int>();
var func = ActionConvert.ToFunc<int>(foo.DoStuff);

You could probably even forego the Unit instance and return null instead.



来源:https://stackoverflow.com/questions/13928963/implement-f-interface-member-with-unit-return-type-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!