简体   繁体   中英

Question regarding fluent interface in C#

I have the following class:

public class Fluently
{
  public Fluently Is(string lhs)
  {
    return this;
  }
  public Fluently Does(string lhs)
  {
    return this;
  }
  public Fluently EqualTo(string rhs)
  {
    return this;
  }
  public Fluently LessThan(string rhs)
  {
    return this;
  }
  public Fluently GreaterThan(string rhs)
  {
    return this;
  }
}

In English grammar you can't have “is something equal to something” or “does something greater than something” so I don't want Is.EqualTo and Does.GreaterThan to be possible. Is there any way to restrict it?

var f = new Fluently();
f.Is("a").GreaterThan("b");
f.Is("a").EqualTo("b");        //grammatically incorrect in English
f.Does("a").GreaterThan("b");
f.Does("a").EqualTo("b");      //grammatically incorrect in English

Thank you!

To enforce that type of thing, you'll need multiple types (to restrict what is available from which context) - or at the least a few interfaces:

public class Fluently : IFluentlyDoes, IFluentlyIs
{
    public IFluentlyIs Is(string lhs)
    {
        return this;
    }
    public IFluentlyDoes Does(string lhs)
    {
        return this;
    }
    Fluently IFluentlyDoes.EqualTo(string rhs)
    {
        return this;
    }
    Fluently IFluentlyIs.LessThan(string rhs)
    {
        return this;
    }
    Fluently IFluentlyIs.GreaterThan(string rhs)
    {
        return this;
    }
}
public interface IFluentlyIs
{
    Fluently LessThan(string rhs);
    Fluently GreaterThan(string rhs);
}
public interface IFluentlyDoes
{    // grammar not included - this is just for illustration!
    Fluently EqualTo(string rhs);
}

My solution would be

public class Fluently
{
    public FluentlyIs Is(string lhs)
    {
        return this;
    }
    public FluentlyDoes Does(string lhs)
    {
        return this;
    }
}

public class FluentlyIs
{
    FluentlyIs LessThan(string rhs)
    {
        return this;
    }
    FluentlyIs GreaterThan(string rhs)
    {
        return this;
    }
}

public class FluentlyDoes
{
    FluentlyDoes EqualTo(string rhs)
    {
        return this;
    }
}

Quite similar to Gravell's, but slightly simpler to understand, in my opinion.

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