本文介绍了解释泛型在C#深入浅出的风格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


其实我想知道什么时候应该使用泛型和为什么?

Actually i want to know 'why and when should i use generics?'.

什么需要吗?

推荐答案

泛型是确保类型安全在编译的时候在C#中的一种方式。

Generics are a way of ensuring Type Safety at Compile time in C#.

例 - 预泛型:

class Person 
{
 string name;
 string lastname;
 public Person(string _name )  { this.name = _name; }
}

class ClientCode
{
   public static void Main()
   {
         //create a list of person
         ArrayList personList = new ArrayList();
         Person p1 = new Person("John");
         Person p2 = new Person("Ram");
         personList.Add(p1);
         personList.Add(p2);
         // BUT, someone can do something like:
         // ArrayList does not stop adding another type of object into it
         object q = new object();
         personList.Add(q);
         // while accessing personlist
         foreach(object obj in personlist)
         {
            Person p = obj as Person;
            // do something, for person
            // But it will fail for last item in list 'q' since its is not person.
         }
   }
}



例 - 后泛型:

Example- Post-Generics:

class ClientCode
{
   public static void Main()
   {
         //create a list of person
         List<Person> personList = new List<Person>();
         Person p1 = new Person("John");
         Person p2 = new Person("Ram");
         personList.Add(p1);
         personList.Add(p2);
         // Someone can not add any other object then Person into personlist
         object q = new object();
         personList.Add(q); // Compile Error.
         // while accessing personlist, No NEED for TYPE Casting
         foreach(Person obj in personlist)
         {
            // do something, for person
         }
   }
}

这篇关于解释泛型在C#深入浅出的风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 22:25