有关C#中流畅界面的问题

时间:2009-08-20 07:25:07

标签: c# fluent-interface

我有以下课程:

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.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

谢谢!

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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相似,但在我看来,理解起来稍微简单一些。