Les méthodes d'extension
De Banane Atomic
Aller à la navigationAller à la recherche
Disponible à partir de C# 3, elles permettent d'ajouter des méthodes à une classe ou à une structure sans en modifier son code.
|
// Déclaration de la méthode d'extension dans une classe static public static class StringExtensions { /// <summary> /// A Contains method with a comparison type. /// </summary> public static bool Contains(this string source, string value, StringComparison comparisonType) { return source.IndexOf(value, comparisonType) >= 0; } } // Utilisation de la méthode d'extension : comparaison de string en ignorant la casse var monString = "ASTRINGTOTEST"; monString.Contains("string", StringComparison.OrdinalIgnoreCase); |
Useful extension methods
CollectionExtensions
public static class CollectionExtensions { /// <summary> /// Adds each item to the list. /// </summary> /// <remarks> /// The <see cref="IList{T}" /> interface does not have AddRange in its contract, contrary to the <see cref="List{T}" /> implementation. /// The latter uses an optimized routine for adding a range of elements, and naming this extension method AddRange too would give the wrong impression of performance. /// Additionally, for collections that notify of their changes, AddRange reads as if there would be only one notification of change after all elements have been added, when in fact there would probably by as many notifications as items being added. /// </remarks> public static void AddEach<T>(this ICollection<T> collection, IEnumerable<T> elements) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if (elements == null) { throw new ArgumentNullException(nameof(elements)); } if (collection is List<T> list) { list.AddRange(elements); } else { foreach (var element in elements) { collection.Add(element); } } } /// <summary> /// Removes each item from the list. /// </summary> /// <remarks> /// This method is not named RemoveRange, because it does not have the same purpose as <see cref="List{T}.RemoveRange" />. /// </remarks> public static void RemoveEach<T>(this ICollection<T> collection, IEnumerable<T> elements) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if (elements == null) { throw new ArgumentNullException(nameof(elements)); } foreach (var element in elements) { collection.Remove(element); } } } |