public class A<T>{}
这啥意思啊,谁能给个例子效习效习
这啥意思啊,谁能给个例子效习效习
解决方案 »
- 枚举类型这样定义大家看看可以不
- win2008远程桌面断开后,按键精灵程序不能进行运行,怎么解决呢?
- 文件上传错误,求指教!
- 求教下,大家现在都用什么工作流?
- 【线程的简单问题】
- 那位对C#熟悉,指点下为什么我抓取得网页都乱码?
- 关于Cookie的问题 迷惑不解
- ComboBox.selectItem的问题(C#/WinForm)
- 跪求帮助:设计一个用户界面调用ping命令,如果不能ping通则在界面提示:网络不通!
- wpf新建类修改textbox控件属性问题
- 高人指点,为什么数据库中查询的结果和在程序中监视的时候 结果不一样???????????????????????????
- 怎么把所有的字母、标点符号替换成空???是用正则表达试吗??希望高手帮忙!!!!!!
using System.Collections.Generic;
using System.Text;namespace BCLTest
{
public static class Singleton<T>
{
private static T instance; public static T NewInstance()
{
if (instance == null)
{
instance = (T)Activator.CreateInstance(typeof(T), true);
} return instance;
}
} public class Class1
{
private Class1() { }
} public class Class2
{
private Class2() { }
}}
public static T Add(float A1,float A2){
return (T)(A1+A2);
}
} A<int>.Add(3.1,3.2)
将返回int型
A<float>.Add(3.1,3.2)
将返回float型一个泛型就顶替了两个类:
public class A {
public static int Add(float A1,float A2){
return (int)(A1+A2);
}
}
和
public class A {
public static float Add(float A1,float A2){
return (float)(A1+A2);
}
}泛型是弱类型,就是在运行时才知道具体的类型,就容易出错。比如:
A<float>.Add("1212",3.2)
编译不出错,但运算执行的时候就出错了。
// 尖括号中的类型参数 T。
public class MyList<T> : IEnumerable<T>
{
protected Node head;
protected Node current = null; // 嵌套类型也是 T 上的泛型
protected class Node
{
public Node next;
// T 作为私有成员数据类型。
private T data;
// 在非泛型构造函数中使用的 T。
public Node(T t)
{
next = null;
data = t;
}
public Node Next
{
get { return next; }
set { next = value; }
}
// T 作为属性的返回类型。
public T Data
{
get { return data; }
set { data = value; }
}
} public MyList()
{
head = null;
} // T 作为方法参数类型。
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
} // 实现 GetEnumerator 以返回 IEnumerator<T>,从而启用列表的
// foreach 迭代。请注意,在 C# 2.0 中,
// 不需要实现 Current 和 MoveNext。
// 编译器将创建实现 IEnumerator<T> 的类。
public IEnumerator<T> GetEnumerator()
{
Node current = head; while (current != null)
{
yield return current.Data;
current = current.Next;
}
} // 必须实现此方法,因为
// IEnumerable<T> 继承 IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}