简体   繁体   中英

Return F# Interface from C# Method

I'm re-coding some things from F# to C# and have come across a problem.

In the F# example I have something like this:

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() = () }

Now in my C# version I have..

public class Derp
{
    // stuff

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

How would I recreate that F# functionality in C#? Is there any way to do it without fully redefining the ITest interface in C#?

C# does not support defining an anonymous implementation of an interface like that. Alternatively, you could declare some inner class and return that instead. Example:

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

Note that I'm not sure I got the types correctly for your F# code, but that should be the general idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM