« Les méthodes d'extension » : différence entre les versions
Apparence
Ligne 24 : | Ligne 24 : | ||
= Useful extension methods = | = Useful extension methods = | ||
== | == CollectionExtension == | ||
<kode lang="cs" collapsed> | <kode lang="cs" collapsed> | ||
public static class | public static class CollectionExtension | ||
{ | { | ||
/// <summary> | /// <summary> | ||
Ligne 106 : | Ligne 106 : | ||
} | } | ||
</kode> | </kode> | ||
== IEnumerableExtension == | |||
<filebox fn='IEnumerableExtension.cs' collapsed> | |||
public static IEnumerable<T> OrderBy<T>( | |||
this IEnumerable<T> source, | |||
string propertyName, | |||
bool ascendingOrder) | |||
{ | |||
var propertyDescriptor = TypeDescriptor.GetProperties(typeof(T)) | |||
.Find(propertyName, false); | |||
if (propertyDescriptor == null) | |||
throw new Exception($"Property '{propertyName}' not found."); | |||
return ascendingOrder ? | |||
source.OrderBy(x => propertyDescriptor.GetValue(x)) : | |||
source.OrderByDescending(x => propertyDescriptor.GetValue(x)); | |||
} | |||
</filebox> |
Version du 27 janvier 2022 à 21:52
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
CollectionExtension
|
IEnumerableExtension
IEnumerableExtension.cs |