日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

【读书笔记】泛型接口 和 泛型方法

發(fā)布時(shí)間:2024/4/14 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【读书笔记】泛型接口 和 泛型方法 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

使用泛型可以定義接口,接口中的方法可以帶泛型參數(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í)候

// 加強(qiáng)版的泛型方法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;} }

?

調(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。