Pattern builder in C#

Livello 5278 battiture

Implementa il pattern builder con concatenamento di metodi per costruire una stringa di query.

Codice C#

// Il concatenamento di metodi costruisce la query passo dopo passo
1var q = new Query()
2 .From("users")
3 .Where("age>20");
// WriteLine chiama ToString: FROM users WHERE age>20
4Console.WriteLine(q);
// La classe builder accumula stato
5class Query
6{
// Campi privati per tabella e clausola where
7 string t = "", w = "";
// From imposta la tabella e restituisce this per il concatenamento
8 public Query From(string s)
9 { t = s; return this; }
// Where imposta la condizione e restituisce this
10 public Query Where(string s)
11 { w = s; return this; }
// ToString produce la stringa di query finale
12 public override string ToString()
13 => $"FROM {t} WHERE {w}";
14}

Output

FROM users WHERE age>20
Esercitati a digitare questo codice

Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.

Simboli in questo codice

I simboli che digiti in questo codice C# e quante volte compaiono.

  • "× 10
  • ;× 8
  • (× 7
  • )× 7
  • =× 6
  • {× 5
  • }× 5
  • .× 3
  • >× 2
  • ,× 1

Altri esempi C# di livello 5

← Pratica di digitazione C#