关于C#中流畅接口的问题

5

我有以下的类:

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

在英语语法中,你不能使用“is something equal to something”或者“does something greater than something”,因此我不希望出现Is.EqualTo和Does.GreaterThan。有没有办法限制它们的使用?

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

谢谢!


你确定“is something equal to something”在语法上是不正确的吗? - Darko
也许不是完全正确,但你能理解我的意思吧? - Jeff
是的,我明白了,我认为这与上下文有关。你是在询问它是否相等还是在陈述它相等吗?如果我知道答案,我会回答你的问题,但说实话,我不确定,所以我正在成为语法纳粹 :) - Darko
2个回答

9
为了强制执行这种类型的事情,您将需要多种类型(以限制哪些上下文中可用)-或者至少几个接口:
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);
}

0

我的解决方案是

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

我认为这个与Gravell的相似,但稍微更容易理解一些。


我更喜欢Gravell的解决方案,因为我可以将单个类拆分为部分类以提高可读性。 - Jeff

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