【読書ノート】汎用インタフェースと汎用方法
3426 ワード
汎用を使用してインタフェースを定義し、インタフェースのメソッドは汎用パラメータを持つことができます.
次に、汎用インタフェースの例を示します.
Personクラスの実装:
汎用タイプを定義するほか、汎用メソッドを定義することもできます.汎用メソッドでは、汎用タイプはメソッド宣言で定義されます.
次の例では、交換の一般的な方法を示します.
汎用メソッドの呼び出しには、次の2つの方法があります.
一、汎用タイプ付与メソッド呼び出し
あるいは、C#コンパイラがSwapメソッドを呼び出すことによってパラメータのタイプを取得するため、非汎用メソッドのように直接呼び出されます.
次の例では、汎用メソッドを使用して、セット内のすべての要素を累積します.
上記の従来の方法を使用すると、Accountオブジェクトにのみ適用できる問題があります.
foreach(Account a in e)がこの方法をすべてのオブジェクトに適用する場合に拡張する
呼び出しは2つの方法でこの汎用的な方法を呼び出すことができます.
decimal amount = Algorithm.Accumulate(accounts);
または、
decimal amount = Algorithm.Accmulate(accounts);
次に、汎用インタフェースの例を示します.
public interface IComparable<T>
{
int CompareTo(T other);
}
Personクラスの実装:
public class Person : IComparable<Person>
{
public int CompareTo(Person obj)
{
return this.lastname.CompareTo(other.lastname);
}
}
汎用タイプを定義するほか、汎用メソッドを定義することもできます.汎用メソッドでは、汎用タイプはメソッド宣言で定義されます.
次の例では、交換の一般的な方法を示します.
void Swap<T>(ref T x, ref T y)
{
T temp;
temp = x;
x = y;
y = temp;
}
汎用メソッドの呼び出しには、次の2つの方法があります.
一、汎用タイプ付与メソッド呼び出し
int i = 4;
int j = 5;
Swap<int>(ref i, ref j);
あるいは、C#コンパイラがSwapメソッドを呼び出すことによってパラメータのタイプを取得するため、非汎用メソッドのように直接呼び出されます.
int i = 4;
int j = 5;
Swap(ref i, ref j);
次の例では、汎用メソッドを使用して、セット内のすべての要素を累積します.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace GenericMethod
{
public class Account
{
private string name;
public string Name
{
get
{
return name;
}
}
private decimal balance;
public decimal Balance
{
get
{
return balance;
}
}
public Account(string name, decimal balance)
{
this.name = name;
this.balance = balance;
}
}
// foreach Account
public static class Algorithm
{
public static decimal AccumulateSimple(IEnumerable e)
{
decimal sum = 0;
foreach (Account a in e)
{
sum += a.Balance;
}
return sum;
}
}
class Program
{
static void Main(string[] args)
{
List<Account> accounts = new List<Account>();
accounts.Add(new Account("Christian", 1500));
accounts.Add(new Account("Sharon", 2200));
accounts.Add(new Account("Katie", 1800));
decimal amount = Algorithm.AccumulateSimple(accounts);
Console.WriteLine(amount.ToString());
Console.ReadLine();
}
}
}
上記の従来の方法を使用すると、Accountオブジェクトにのみ適用できる問題があります.
foreach(Account a in e)がこの方法をすべてのオブジェクトに適用する場合に拡張する
//
public class Account : IAccount
{
//...
}
public interface IAccount
{
decimal Balance
{
get;
}
string Name
{
get;
}
}
public static class Algorithm
{
public static decimal AccumulateSimple<TAccount>(IEnumerable<TAccount> coll) where TAccount : IAccount
{
decimal sum = 0;
foreach (TAccount a in coll)
{
sum += a.Balance;
}
return sum;
}
}
呼び出しは2つの方法でこの汎用的な方法を呼び出すことができます.
decimal amount = Algorithm.Accumulate
または、
decimal amount = Algorithm.Accmulate(accounts);