【读书笔记】泛型接口 和 泛型方法
使用泛型可以定義接口,接口中的方法可以帶泛型參數(shù)。
下面是一個(gè)泛型接口的例子:
public interface IComparable<T> {int CompareTo(T other); }?
對(duì)于一個(gè)Person類的實(shí)現(xiàn):
public class Person : IComparable<Person> {public int CompareTo(Person obj){return this.lastname.CompareTo(other.lastname);} }?
除了定義泛型類型之外,還可以定義泛型方法。 在泛型方法中,泛型類型用方法聲明來定義。
下面示例一個(gè)交換的泛型方法:
void Swap<T>(ref T x, ref T y) {T temp;temp = x;x = y;y = temp; }?
泛型方法的調(diào)用,有兩種方法:
一, 把泛型類型賦予方法調(diào)用
int i = 4; int j = 5; Swap<int>(ref i, ref j);?
或者直接像非泛型方法那樣調(diào)用, 這是因?yàn)镃#編譯器會(huì)通過調(diào)用Swap方法來獲取參數(shù)的類型。
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;}}// 傳統(tǒng)方法 使用foreach語句迭代所有的Account對(duì)象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();}} }?
當(dāng)使用上面的傳統(tǒng)方法的時(shí)候就會(huì)有一個(gè)問題, 它只能適用于Account對(duì)象
?foreach (Account a in e)
將這個(gè)方法擴(kuò)充到對(duì)所有對(duì)象適用的時(shí)候
?
調(diào)用可以采用2種方法來調(diào)用這個(gè)泛型方法了:
decimal amount = Algorithm.Accumulate<Account>(accounts);
或者:
decimal amount = Algorithm.Accmulate(accounts);
轉(zhuǎn)載于:https://www.cnblogs.com/herbert/archive/2010/05/26/1744407.html
總結(jié)
以上是生活随笔為你收集整理的【读书笔记】泛型接口 和 泛型方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 过滤XML数据中的非主流特殊字符
- 下一篇: VS2010 IDE新特性随笔