【读书笔记】泛型接口 和 泛型方法
生活随笔
收集整理的這篇文章主要介紹了
【读书笔记】泛型接口 和 泛型方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用泛型可以定義接口,接口中的方法可以帶泛型參數。
下面是一個泛型接口的例子:
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; }?
泛型方法的調用,有兩種方法:
一, 把泛型類型賦予方法調用
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)
將這個方法擴充到對所有對象適用的時候
?
調用可以采用2種方法來調用這個泛型方法了:
decimal amount = Algorithm.Accumulate<Account>(accounts);
或者:
decimal amount = Algorithm.Accmulate(accounts);
轉載于:https://www.cnblogs.com/herbert/archive/2010/05/26/1744407.html
總結
以上是生活随笔為你收集整理的【读书笔记】泛型接口 和 泛型方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 过滤XML数据中的非主流特殊字符
- 下一篇: ASP.NET 4新增功能(三) 对We