C'è un modo per ridurre il livello di dettaglio di utilizzare String.Format (..., p1, p2, p3)?

StackOverflow https://stackoverflow.com/questions/2774498

  •  03-10-2019
  •  | 
  •  

Domanda

Io uso spesso String.Format() perché rende la costruzione di stringhe più leggibili e gestibili.

Esiste un modo per ridurre la sua prolissità sintattica, per esempio con un metodo di estensione, ecc.?

Logger.LogEntry(String.Format("text '{0}' registered", pair.IdCode));

public static void LogEntry(string message)
{
    ...
}

es. Vorrei utilizzare tutte le mie e di altri metodi che ricevono una stringa il modo in cui io uso Console.Write(), per esempio:.

Logger.LogEntry("text '{0}' registered", pair.IdCode);
È stato utile?

Soluzione

Come su:

static void LogEntry(string format, params object[] args) {
    Console.WriteLine(format, args); // For example.
}

Ora si può chiamare in questo modo:

Logger.LogEntry("text '{0}' registered", pair.IdCode);

Altri suggerimenti

Se controlli il metodo Logger.LogEntry, si può semplicemente aggiungere un sovraccarico che racchiude lo String.Format. Basta dichiarare il secondo parametro come un ParamArray e siete pronti per partire!

Sì, è possibile effettuare un metodo di estensione di nome FormatWith, che consente di dire le cose come:

Logger.LogEntry("I hate my {0}".FormatWith(itemName));

Dovrebbe essere abbastanza facile da rotolare il proprio, ma ecco un esempio: http://james.newtonking.com/archive/2008/03/27/formatwith-string-format-extension-method.aspx

Se Logger.LogEntry è un metodo al di fuori statica del vostro controllo, allora no; si può solo aggiungere metodi di estensione alle istanze. Se è il tuo tipo, si potrebbe aggiungere:

public static void LogEntry(string format, params object[] args) {
    ... string.Format(format,args) ...
}

È possibile utilizzare i params parola chiave per combinare tutti gli argomenti che seguono il primo argomento in un array e passare tale matrice a String.Format.

static void FormatString(string myString, params string[] format)
{
     Console.WriteLine(String.Format(myString, format));
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top