|
此文章由 dalaohu 原创或转贴,不代表本站立场和观点,版权归 oursteps.com.au 和作者 dalaohu 所有!转贴必须注明作者、出处和本声明,并保持内容完整
占个坑。 Generic by definition.
* generic 有些人叫他 type-safe.
What Are Generics
Generics allow you to define type-safe classes without compromising type safety, performance, or productivity. You implement the server only once as a generic server, while at the same time you can declare and use it with any type. To do that, use the < and > brackets, enclosing a generic type parameter.
Generics Benefits
Generics in .NET let you reuse code and the effort you put into implementing it. The types and internal data can change without causing code bloat, regardless of whether you are using value or reference types. You can develop, test, and deploy your code once, reuse it with any type, including future types, all with full compiler support and type safety. Because the generic code does not force the boxing and unboxing of value types, or the down casting of reference types, performance is greatly improved. With value types there is typically a 200 percent performance gain, and with reference types you can expect up to a 100 percent performance gain in accessing the type (of course, the application as a whole may or may not experience any performance improvements). The source code available with this article includes a micro-benchmark application, which executes a stack in a tight loop. The application lets you experiment with value and reference types on an Object-based stack and a generic stack, as well as changing the number of loop iterations to see the effect generics have on performance.
public class Point<T>
{
public T X;
public T Y;
}
You can use the generic point for integer coordinates, for example:
Point<int> point;
point.X = 1;
point.Y = 2;
Or for charting coordinates that require floating point precision:
Point<double> point;
point.X = 1.2;
point.Y = 3.4;
Multiple Generic Types
class Node<K,T>
{
public K Key;
public T Item;
public Node()
{
Key = default(K);
Item = defualt(T);
}
public Node(K key,T item)
{
Key = key;
Item = item;
}
}
var node = new Node<int,string>();
or
var node = new Node<int,string>(123, "ABC");
说白了generic的引入,就是程序的reusability跟高了一点的
[ 本帖最后由 dalaohu 于 2010-3-30 23:23 编辑 ] |
|