泛型
来源:互联网 发布:c语言可视化软件 编辑:程序博客网 时间:2024/06/07 06:44
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace MyConsole
{
class Program
{
static void Main(string[] args)
{
// 测试范型集合
List<Person> plist = new List<Person>();
plist.Add(new Person("A", 10, Genders.Male));
plist.Add(new Person("B", 13, Genders.Male));
plist.Add(new Person("C", 20, Genders.Female));
plist.Add(new Person("D", 45, Genders.Male));
foreach (Person p in plist)
{
Console.WriteLine("{0}-{1}-{2}", p.Name, p.Age, p.Gender);
}
Dictionary<string, Person> pdic = new Dictionary<string, Person>();
foreach (Person p in plist)
{
pdic.Add(p.Name, p);
}
foreach (Person p in plist)
{
Console.WriteLine("{0}-{1}-{2}", p.Name, p.Age, p.Gender);
}
/////////////////////////////////////////////////////////////////////
// 范型类型
int a = 1, b = 2;
Swap<int>(ref a, ref b);
Console.WriteLine("a={0}, b={1}", a, b);
long al = 1, bl = 2;
Swap<long>(ref al, ref bl);
GClass<int> gc = new GClass<int>(100);
gc.PrintString();
// 范型接口限定
KingTDoc ktd = new KingTDoc();
MyGeneric<KingTDoc> gktd = new MyGeneric<KingTDoc>();
gktd.PrintTitle(ktd);
Console.Read();
}
/// <summary>
/// 范型方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="x"></param>
/// <param name="y"></param>
static void Swap<T> (ref T x, ref T y)
{
T temp = x;
x = y;
y = temp;
}
}
// 范型类型
public class GClass<T>
{
private T t;
public GClass(T v)
{
t = v;
}
public void PrintString()
{
Console.WriteLine(t.ToString());
}
}
////////////////////////////////////////////
// 限定接口的类型
// 先定义一个interface
public interface IDocument
{
string Title {get;}
string Content {get;}
}
// 让范型类T实现这个interface
public class MyGeneric<T> where T : IDocument
{
public void PrintTitle(T v)
{
Console.WriteLine(v.Title);
}
}
public class KingTDoc : IDocument
{
#region IDocument 成员
public string Title
{
get
{
return "KingTDoc_Title";
}
}
public string Content
{
get
{
return "KingTDoc_Content";
}
}
#endregion
}
}
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- Eclipse 3.5 中的jvm terminated.Exit code=-1错误的解决
- GridView序号列
- 坐标系统详解
- 按鼠標效果(http://hi.baidu.com/xuexiang516168/blog/item/01d36144afaebb3586947367.html)
- C++中的动态空间扩充方法
- 泛型
- iis发布asp.net解析 全过程配置http://hi.baidu.com/xuexiang516168/blog/item/afb62317815fdb12962b433c.html
- 第一次使用flash
- oracle lob 简单介绍
- TheadLocal 简明解释
- asp.net javascript回车键事件http://hi.baidu.com/xuexiang516168/blog/item/90f2bc4bc316372908f7eff4.html
- 用C#实现中文验证码
- Oracle数据库Where条件执行顺序
- InfoQ中文站总编辑推荐《软件设计精要与模式(第2版)》