public class A<T>{}
这啥意思啊,谁能给个例子效习效习
这啥意思啊,谁能给个例子效习效习
解决方案 »
- C# 字符串读取问题
- 本人在线等~~~有个有关SQL的问题,请大家帮忙。。。急急急
- 关于ListView修改项的问题
- .NET1.1版的程序调用.NET2.0编译的DLL的问题
- 我是个初学者有几个问题想请教
- c#使用axwebbrowser获得web的内容的时候,如果web页面使用了form,怎么获得内容?
- SplitContainer分隔线
- 求关于asp.net或SQL或C#的英文译文,提供者都给分,谢谢
- 请问用listview能做成一个图标接一个图标的样子么?
- 在开发MIS系统,由数据层的数据表到业务层的业务对象一般使用什么模式?
- 高人指点,为什么数据库中查询的结果和在程序中监视的时候 结果不一样???????????????????????????
- 怎么把所有的字母、标点符号替换成空???是用正则表达试吗??希望高手帮忙!!!!!!
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();
}
}