http://mgc.ahau.edu.cn/article.asp?id=616
C#中使用where子句限制泛型方法的泛型类型。
1.要求泛型类型实现一个接口或派生于某个基类;
2.不能定义必须由泛型类型实现的运算符。
TestMethodTTwo.cs:
- using System;
- using System.Collections.Generic;
- namespace Magci.Test.Collections
- {
- //定义接口
- public interface IAccount
- {
- string Name
- {
- get;
- }
- decimal Balance
- {
- get;
- }
- }
- public class Account : IAccount
- {
- 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;
- }
- }
- public class Algorithm
- {
- //声明泛型方法
- public static decimal Total<TAccount>(IEnumerable<TAccount> e)
- //使用where子句限制泛型类型
- where TAccount : IAccount
- {
- decimal total = 0;
- foreach (TAccount a in e)
- {
- total += a.Balance;
- }
- return total;
- }
- }
- public class TestMethodTTwo
- {
- public static void Main()
- {
- List<Account> accounts = new List<Account>();
- accounts.Add(new Account("Magci", 9999.99m));
- accounts.Add(new Account("Haha", 1241.33m));
- accounts.Add(new Account("Heihei", 1551.2m));
- accounts.Add(new Account("Kevin", 2643m));
- //调用泛型方法
- decimal total = Algorithm.Total(accounts);
- Console.WriteLine("Total : {0:C}", total);
- }
- }
- }