简体   繁体   中英

FunctionalInterface with default methods in C#

I have this FunctionalInterface in Java which I'm trying to port to C#, but not sure how to go about it. I have been looking into delegates but seem to get stuck on the default methods in the Java interface.

@FunctionalInterface
public interface MyFunction
{
  boolean apply(Argument p);

  default MyFunction and(MyFunction after) {
    return (p) -> {
      Argument copyP = new Argument(p);
      boolean applied = this.apply(copyP) && after.apply(copyP);
      if(applied){
        // boilerplate work
      }
      return applied;
    };
  }

  default MyFunction or(MyFunction after) {
    return (p) -> {
      boolean applied = this.apply(p);
      return applied || after.apply(p);
    };
  }
}

If I would just need the apply method I could easily port this to a delegate:

public delegate bool MyFunction(Argument p);

However, the point of my code is to chain different MyFunction 's together with the and / or methods and only apply the work if the logical condition is met. If anyone could point me in the right direction on how to deal with the above interface in C# it would be greatly appreciated.

MyFunction should be, as you said, a delegate in C#. You can use extension methods on MyFunction to simulate and and or :

// in a static class
public static MyFunction And(this MyFunction f, MyFunction after) =>
    p => {
      Argument copyP = new Argument(p);
      boolean applied = f(copyP) && after(copyP);
      if(applied){
        // boilerplate work
      }
      return applied;
    };

public static MyFunction Or(this MyFunction f, MyFunction after) =>
    p => {
        var applied = f(p);
        return applied || after(p);
    };

Also, you might want to consider the possibility of not creating an entirely new type at all. In C#, Predicate<Argument> has exactly the same signature as MyFucntion , so you could just write extension methods for Predicate<Argument> instead of MyFunction , and deleting MyFunction all together.

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