Datgs' Blog

Quyết chiến quyết thắng !

Archive for the tag “generics”

C# Generics

Kiểu mảng cũ

using System;

using System.Collections;

namespace TestApp {

class Test {

[STAThread]

static void Main(string[] args) {

ArrayList list = new ArrayList();

list.Add(3);

list.Add(4);

//list.Add(5.0);

int total = 0;

foreach(int val in list) {

total = total + val;

}

Console.WriteLine( “Total is {0}”, total);

}

}

}

Generics

List<int> aList = new List<int>();

aList.Add(3);

aList.Add(4);

// aList.Add(5.0);

int total = 0;

foreach(int val in aList) {

total = total + val;

}

Console.WriteLine(“Total is {0}”, total);

Viết generics class

//MyList.cs

#region Using directives

using System;

using System.Collections.Generic;

using System.Text;

#endregion

namespace CLRSupportExample {

public class MyList<T> {

private static int objCount = 0;

public MyList() { objCount++; }

public int Count {

get { return objCount; }

}

}

}

//Program.cs

#region Using directives

using System;

using System.Collections.Generic;

using System.Text;

#endregion

namespace CLRSupportExample {

class SampleClass {}

class Program {

static void Main(string[] args) {

MyList<int> myIntList = new MyList<int>();

MyList<int> myIntList2 = new MyList<int>();

MyList<double> myDoubleList = new MyList<double>();

MyList<SampleClass> mySampleList = new MyList<SampleClass>();

Console.WriteLine(myIntList.Count);

Console.WriteLine(myIntList2.Count);

Console.WriteLine(myDoubleList.Count);

Console.WriteLine(mySampleList.Count);

Console.WriteLine( new MyList<sampleclass>().Count);

Console.ReadLine();

}

}

}

Methods với Generics

public class Program {

public static void Copy<T>(List<T> source, List<T> destination){

foreach (T obj in source) {

destination.Add(obj);

}

}

static void Main(string[] args)

{

List<int> lst1 = new List<int>();

lst1.Add(2);

lst1.Add(4);

List<int> lst2 = new List<int>();

Copy(lst1, lst2);

Console.WriteLine(lst2.Count);

}

}

Java Generics

Example generic class:

public class Pair<T, S>
{
/* construct*/
  public Pair(T f, S s)
  {
    first = f;
    second = s;
  }
 
/*set / get*/
  public T getFirst()
  {
    return first;
  }

  public S getSecond()
  {
    return second;
  }

  public String toString()
  {
    return "(" + first.toString() + ", " + second.toString() + ")";
  }

  private T first;
  private S second;
 /*định nghĩa phương thưcs twice*/
  public <T> Pair<T,T> twice(T value)
  {
     return new Pair<T,T>(value,value);
  }

}

Use:

Pair<String, String> grade440 = new Pair<String, String>("mike", "A");
Pair<String, Integer> marks440 = new Pair<String, Integer>("mike", 100);
System.out.println("grade:" + grade440.toString());
System.out.println("marks:" + marks440.toString());
Uses twice:
Pair<String, String> pair = twice("Hello");

Post Navigation

Follow

Get every new post delivered to your Inbox.