本文介绍了在C#中用Unit返回类型实现F#接口成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

如果我在C#中实现此功能,则需要方法签名为:

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

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

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

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

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

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

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?

推荐答案

Unit转换为void的过程包含在编译器中. F#Core中有一个 FuncConvert 类,用于在FSharpFunc之间进行转换和Converter.定义一个类似的类将Action<T>转换为Func<T, Unit>怎么样?

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);
    }
}

那你可以做

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

您甚至可以放弃Unit实例,而返回null.

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

这篇关于在C#中用Unit返回类型实现F#接口成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:34