从C#方法返回F#接口

4
我正在将一些东西从F#重新编码为C#,遇到了一个问题。
在F#示例中,我有这样的内容:
let foo (x:'T) =
    // stuff
    { new TestUtil.ITest<'T[], 'T[]> with
        member this.Name input iters = "asdfs"
        member this.Run input iters = run input iters
      interface IDisposable with member this.Dispose() = () }

现在在我的C#版本中,我有...
public class Derp
{
    // stuff

    public TestUtil.ITest<T, T> Foo<T>(T x)
    {
        // ???
        // TestUtil.ITest is from an F# library
    }
}

我该如何在C#中重现那个F#功能呢?是否有任何方法可以在不完全重新定义ITest接口的情况下实现它?

你能详细描述一下你需要的功能是什么吗? - MisterMetaphor
1个回答

6

C#不支持定义类似于匿名实现接口的方式。作为替代方案,您可以声明一些内部类并返回它们。例如:

public class Derp
{
    class Test<T> : TestUtil.ITest<T, T>
    {
        public string Name(T[] input, T[] iters) 
        {
            return "asdf";
        }
        public void Run(T[] input, T[] iters)
        {
             run(input, iters);
        }
        public void Dispose() {}
    }

    public TestUtil.ITest<T, T> Foo<T>(T x)
    {
         //stuff
         return new Test<T>();
    }
}

请注意,我不确定您的F#代码的类型是否正确,但这应该是一般想法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接