Not required to assign the generic type with the method call. The generic method can be invoked as simply
as non-generic methods:
int i = 4;
int j = 5;
Swap(ref i, ref j);
Desc: To show the features of generic methods, assume the following Account class that contains Name and Balance properties.All the accounts where the balance should be accumulated are added to an accounts list of type
List<Account>:
var accounts = new List<Account>()
{new Account("Christian", 1500),
new Account("Stephanie", 2200),
new Account("Angela", 1800)};
to accumulate all Account objects is by looping through all Account objects with a foreach statement, as shown here. Because the foreach statement uses the IEnumerable interface to iterate the elements of a collection.The foreach statement works with every object implementing IEnumerable. This way, the AccumulateSimple() method can be used with all collection classes that implement the interface IEnumerable<Account>. In the implementation of this method, the property Balance of the Account
object is directly accessed:
Public static class Algorithm
{
public static decimal AccumulateSimple(IEnumerable<Account> source)
{
decimal sum = 0;
Foreach (Account a in source)
{
sum += a.Balance;
}
return sum;
}
}
The AccumulateSimple() method is invoked this way:
decimal amount = Algorithm.AccumulateSimple(accounts);
Дата добавления: 2015-09-18 | Просмотры: 505 | Нарушение авторских прав
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
|