c# - 在 C# 中以通俗易懂的方式解释泛型?

标签 c# generics

<分区>

重复 What is the "< >" syntax within C#


实际上我想知道“为什么以及什么时候应该使用泛型?”。

有什么必要呢?

最佳答案

泛型是在 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.
         }
   }
}

示例-后泛型:

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# - 在 C# 中以通俗易懂的方式解释泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/713438/

相关文章:

c# - 谁能理解/解释这个字符串扩展?

c# - 在 Windows 中覆盖的透明窗口应用程序

swift - 在数组中使用 PAT 存储通用结构的一些问题

generics - 是否可以用 VHDL 编写类型通用实体?

c# - 为什么下面的代码不能编译?

c# - CLR 中的空引用检查

c# - 如何在 jquery 变量中获取业务类属性值

c# - 图表的轴值格式

ios - 泛型不适用于隐式解包的可选

c# - 没有对系统 IDispose 的隐式引用转换