C#中使用where子句限制泛型方法的泛型类型
2009-07-28 13:48
741 查看
http://mgc.ahau.edu.cn/article.asp?id=616
C#中使用where子句限制泛型方法的泛型类型。
1.要求泛型类型实现一个接口或派生于某个基类;
2.不能定义必须由泛型类型实现的运算符。
TestMethodTTwo.cs:
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); } } }
相关文章推荐
- c# 泛型 类型参数上的限制(where T:class,new())
- 使用 where 子句约束泛型类型
- More Effective C# Item8 :尽可能使用泛型方法,除非需要将类型参数用于实例的字段中
- 使用C#反射中的MakeGenericType函数,来为泛型方法和泛型类指定(泛型的)类型
- 使用C#反射中的MakeGenericType函数,来为泛型方法和泛型类指定(泛型的)类型
- 30天C#基础巩固-----值类型/引用类型,泛型,空合并操作符(??),匿名方法
- 使用泛型, 写一个为任意类型的动态数组添加元素的方法
- java中的方法返回值使用泛型,实现灵活的返回值类型
- 针对GROUP BY 设置限制条件,则不能使用Where 子句,必须使用HAVING 子句来设置。
- C# 泛型方法Where 约束
- More Effective C# Item6 : 使用委托定义类型参数上的方法约束
- 【C#小知识】C#中一些易混淆概念总结--------数据类型存储位置,方法调用,out和ref参数的使用
- C#学习笔记三: C#2.0泛型 可控类型 匿名方法和迭代器
- C#基础视频教程3.3 常见控件类型和使用方法
- c# 使用泛型类型作为参数
- 限制泛型可用类型,类型通配符声明,泛型方法
- c#泛型类型的约束条件where
- C# DataTable.Select()方法,条件中使用类型转换
- 编写高质量代码改善C#程序的157个建议[为泛型指定初始值、使用委托声明、使用Lambda替代方法和匿名方法]
- C#中使用委托、接口、匿名方法、泛型委托实现加减乘除算法