Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement generic classes in C #

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

这篇文章主要为大家展示了"C#如何实现泛型类",内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下"C#如何实现泛型类"这篇文章吧。

使用泛型集合

有些人问我"面向对象编程(OOP)的承诺在哪里?",我的回答是应该从两个方面来看OOP:你所使用的OOP和你创建的OOP。如果我们简单地看一下如果没有如例如Microsoft的.NET,Borland的VCL,以及所有的第三方组件这样的OO框架,那么很多高级的应用程序几乎就无法创建。所以,我们可以说OOP已经实现了它的承诺。不错,生产好的OOP代码是困难的并且可能是***挫败性的;但是记住,你不必须一定要通过OOP来实现你的目标。因此,下面首先让我们看一下泛型的使用。

当你用Visual Studio或C# Express等快速开发工具创建工程时,你会看到对于System.Collections.Generic命名空间的参考引用。在这个命名空间中,存在若干泛型数据结构-它们都支持类型化的集合,散列,队列,栈,字典以及链表等。为了使用这些强有力的数据结构,你所要做的仅是提供数据类型。

显示出我们定义一个强类型集合的Customer对象是很容易的:

using System; using System.Collections.Generic; using System.Text; namespace Generics{ class Program{ static void Main(string[] args){ List customers = new List(); customers.Add(new Customer("Motown-Jobs")); customers.Add(new Customer("Fatman's")); foreach (Customer c in customers) Console.WriteLine(c.CustomerName); Console.ReadLine(); } } public class Customer{ private string customerName = ""; public string CustomerName{ get { return customerName; } set { customerName = value; } } public Customer(string customerName){ this.customerName = customerName; } } }

注意,我们有一个强类型集合-List-对这个集合类本身来说不需要写一句代码。如果我们想要扩展列表customer,我们可以通过从List继承而派生一个新类。

C#实现泛型类

一种合理的实现某种新功能的方法是在原有的事物上进一步构建。我们已经了解强类型集合,并知道一种不错的用来构建泛型类的技术是使用一个特定类并删除数据类型。也就是说,让我们定义一个强类型集合CustomerList,并且来看一下它要把什么东西转化成一个泛型类。

定义了一个类CustomerList:

using System; using System.Collections; using System.Text; namespace Generics{ public class CustomerList : CollectionBase{ public CustomerList() { } public Customer this[int index]{ get { return (Customer)List[index]; } set { List[index] = value; } } public int Add(Customer value) {return List.Add(value);} } }以上是"C#如何实现泛型类"这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report