String.Format con formato nullo
-
10-10-2019 - |
Domanda
Qualcuno può spiegare perché si verifica quanto segue:
String.Format(null, "foo") // Returns foo
String.Format((string)null, "foo") // Throws ArgumentNullException:
// Value cannot be null.
// Parameter name: format
Grazie.
Soluzione
La sua chiamare un sovraccarico di diverso.
string.Format(null, "");
//calls
public static string Format(IFormatProvider provider, string format, params object[] args);
MSDN metodo Link che descrive in precedenza.
string.Format((string)null, "");
//Calls (and this one throws ArgumentException)
public static string Format(string format, object arg0);
MSDN metodo Link che descrive in precedenza.
Altri suggerimenti
Dato che funzione sovraccaricata viene chiamata viene determinato in fase di compilazione in base al tipo statico del parametro:
String.Format(null, "foo")
String.Format(IFormatProvider, string, params Object[])
un IFormatProvider vuoto e una stringa di formattazione di " foo", che è perfettamente bene.
D'altra parte,
String.Format((string)null, "foo")
String.Format(string, object)
con null come stringa di formattazione, che genera fa eccezione.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow