2009-08-20 19 views
5

Mam następujące klasy:Pytanie dotyczące płynny interfejs w języku C#

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

W gramatyki angielskiej nie można mieć „to coś równa coś” lub „robi coś większego niż coś”, więc nie wiem chcą, aby Is.EqualTo i Does.GreaterThan były możliwe. Czy istnieje sposób, aby to ograniczyć?

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 

Dziękujemy!

+0

Czy jesteś pewien, że "coś jest czymś równym" jest gramatycznie niepoprawne? –

+0

Może nie, ale masz odpowiedni pomysł? – Jeff

+0

Tak, mam pomysł, myślę o kontekście. Czy * pytasz * czy jest równy lub * stwierdzasz *, że jest równy? Odpowiedziałbym na twoje pytanie, gdybym wiedział, ale żeby powiedzieć prawdę, nie jestem pewien, więc gram nazistami gramatyki :) –

Odpowiedz

9

Aby wymusić tego typu rzeczy, trzeba wiele typów (aby ograniczyć to, co jest dostępne w jakim kontekście) - lub co najmniej kilka interfejsów:

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

o tak ... dzięki. – Jeff

+0

potrzebujemy teraz guru gramatyki! – Jeff

0

Moje rozwiązaniem byłoby

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

Całkiem podobny do Gravell's, ale nieco prostszy do zrozumienia, według mnie.

+0

Preferuję rozwiązanie Gravella, ponieważ mogę podzielić pojedynczą klasę na klasę częściową dla odczytu. – Jeff

Powiązane problemy