Question

Quelqu'un peut-il expliquer pourquoi ce qui suit se produit:

String.Format(null, "foo") // Returns foo
String.Format((string)null, "foo") // Throws ArgumentNullException:
                                   // Value cannot be null. 
                                   // Parameter name: format

Merci.

Était-ce utile?

La solution

L'appel d'une surcharge différente.

string.Format(null, "");  
//calls 
public static string Format(IFormatProvider provider, string format, params object[] args);

MSDN Méthode lien décrivant ci-dessus.

string.Format((string)null, "");
//Calls (and this one throws ArgumentException)
public static string Format(string format, object arg0);

MSDN Méthode lien décrivant ci-dessus.

Autres conseils

Parce que la fonction surchargée est appelée obtient lors de la compilation en fonction du type statique du paramètre:

String.Format(null, "foo")

String.Format(IFormatProvider, string, params Object[]) avec un IFormatProvider vide et une chaîne de mise en forme " foo », ce qui est parfaitement bien.

Par contre,

String.Format((string)null, "foo")

String.Format(string, object) avec null comme une chaîne mise en forme, ce qui jette un exception.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top