System.Collections.ListofTips

February 6, 2008

Ejemplo de Generics

Filed under: ASP.net, C# — José Franco @ 1:15 am

Como algunos sabrán, laburo sobre el Framework 1.1, y muchas cosas sobre las nuevas versiones del Framework, no tuve el placer de experimentar… salvo por algún que otro libro, y algún desarrollo chiquito como pasatiempo, la experiencia es pobre… igual dejo un ejemplo simple de Generics.

También encontré un artículo bastante interesante, como Generics optimiza varios aspectos de nuestras aplicaciones

http://geeks.ms/blogs/juank/archive/2008/01/16/optimizacion-de-codigo-utilizando-generics.aspx

1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace cmdExample
6 {
7 class Program
8 {
class CustomClass
10  {
11  private Object _t;
12  private Object _u;
13
14 public Object T
15  {
16 get { return _t; }
17 set { _t = value; }
18 }
19
20 public Object U
21  {
22 get { return _u; }
23 set { _u = value; }
24
}
25
26 public CustomClass(Object _ct, Object _cu)
27 {
28 _t = _ct;
29 _u = _cu;
30  }
31  }
32
33  static void Main(string[] args)
34  {
35 CustomClass cNumbers = new CustomClass(1223.23, 2);
36 Console.WriteLine((int)cNumbers.T + (int)cNumbers.U);
37
38 }
39 }
40 }

Como ven, tengo una Clase “CustomClass” que solo le envío valores… pero para hacer la operación los estoy casteando a int, van a ver que el compilador no tira error, pero si alta una excepción en tiempo de ejecución.
Por esto mismo, fue la necesidad de Generics.

Implementando Generics, nuestro código quedaría

1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace cmdExample
6 {
7 class Program
8 {
class CustomClassGenerics<PT,PU>
10  {
11  private PT _t;
12  private PU _u;
13
14  public PT T
15  {
16  get { return _t; }
17  set { _t = value; }
18 }
19
20 public PU U
21 {
22 get { return _u; }
23  set { _u = value; }
24 }
25
26  public CustomClassGenerics(PT _ct, PU _cu)
27 {
28 _t = _ct;
29 _u = _cu;
30 }
31 }
32
33  static void Main(string[] args)
34 {
35 CustomClassGenerics<double,int> cNumbers = new CustomClassGenerics<double, int>(1223.23, 2);
36 Console.WriteLine(cNumbers.T + cNumbers.U);
37 }
38 }
39 }

Es Bastante simple, el ejemplo así que no voy a entrar en muchos detalles.

Más información en http://msdn2.microsoft.com/en-us/library/512aeb7t(VS.80).aspx


Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • E-mail this story to a friend!
  • BarraPunto
  • blogmarks
  • co.mments
  • De.lirio.us
  • kick.ie
  • LinkedIn
  • Linkter
  • Live
  • Meneame
  • MyShare
  • Print this article!
  • TwitThis
  • YahooMyWeb
Bookmark and Share:

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress