68. Extension methods meet generics

בהמשך לטיפים האחרונים,

נוכל להשתמש בExtension methods גם על דברים גנריים.

למשל משהו כזה:

מתודה שמחזירה את האיבר הראשון של enumerable:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static T First<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
{
throw new NullReferenceException
("enumerable was null");
}
using (IEnumerator<T> enumerator = enumerable.GetEnumerator())
{
// Enumerable is empty.
if (!enumerator.MoveNext())
{
throw new ArgumentException
("Received an empty enumerable",
"enumerable");
}
else
{
return enumerator.Current;
}
}
}

נוכל לקרוא לה כך:

1
2
3
4
5
6
7
8
9
IEnumerable<string> strings =
new string[]
{
"A new hope",
"The empire strikes back",
"The return of the Jedi"
};
string firstMovie = strings.First<string>(); // A new hope

מה שיפה שוב זה שבעצם יצרנו extension method שעובד על כל IEnumerable<T>.

נוכל למשל גם לכתוב משהו כזה:

1
char firstLetter = "The first letter is 'T'".First<char>();

ממש מגניב.

יום מורחב טוב

שתף