2010-12-12 36 views
5

Quels outils utiles pour la manipulation de chaînes vous devez partager?Quelle est l'aide de chaîne la plus utile que vous avez rencontrée?

J'ai écrit un remplacement pour String.Format(), que je trouve beaucoup plus propre à utiliser:

public static class StringHelpers 
{ 
    public static string Args(this string str, object arg0) 
    { 
     return String.Format(str, arg0); 
    } 

    public static string Args(this string str, object arg0, object arg1) 
    { 
     return String.Format(str, arg0, arg1); 
    } 

    public static string Args(this string str, object arg0, object arg1, object arg2) 
    { 
     return String.Format(str, arg0, arg1, arg2); 
    } 

    public static string Args(this string str, params object[] args) 
    { 
     return String.Format(str, args); 
    } 
} 

Exemple:

// instead of String.Format("Hello {0}", name) use: 
"Hello {0}".Args(name) 

Quels sont les autres aides utiles avez-vous pour les chaînes en C#?

+0

Je n'en utilise pas. Le vôtre a l'air cool. – TarasB

+0

C'est généralement une bonne idée d'inclure un objet CultureInfo avec String.Format. Vous pouvez inclure un CultureInfo par défaut dans votre méthode d'extension. –

+0

Un exemple connexe que vous pourriez trouver intéressant: http://stackoverflow.com/questions/1322037/how-can--create-a-more-user-friendly-string-format-syntax/1322103#1322103 –

Répondre

4

un assez populaire qui est plus d'une méthode d'extension de confort est la suivante:

public static class StringExtensions 
{ 
    public static bool IsNullOrEmpty(this string s) 
    { 
     return String.IsNullOrEmpty(s); 
    } 
} 

Rien de grand, mais l'écriture myString.IsNullOrEmpty() est plus pratique que String.IsNullOrEmpty(myString).

+0

J'utilise pour faites cela, mais rétrospectivement, vous avez décidé de le supprimer parce que vous pourriez appeler une méthode sur un null. –

+0

Alors qu'il est vrai que celui-ci est populaire (et je l'utilise souvent ... sans doute surtout par paresse), je n'en suis pas vraiment fan. Il y a quelques bons arguments contre cela dans ce post: http://stackoverflow.com/questions/790810/is-extending-string-class-with-isnullorempty-confusing –