泛型在C#中的实际应用 [英] Practical use of Generics in C#

查看:72
本文介绍了泛型在C#中的实际应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



我在C#中经历了很多关于泛型的文章,但是无法理解它的实际用途,请问有谁能解释一下我的实时问题是什么不使用泛型类型以及我们如何使用泛型来解决这些问题





谢谢

Hello,

I have gone through many articals about Generics in C# but unable to understand it's Practical use, can anybody please explain me what are the real time problems without using Generic types and how we can solve those using Generics


Thank you

推荐答案

我认为,当你了解泛型,并对如何使用它们有感觉时,你会发现它们非常有用。我还预测你对Generics可以用来做什么感觉......并且大大简化......的编码将会进入阶段。



所以,让我概述一下我认为Generics为.NET添加的主要好处,按照我认为易于理解的顺序,以及它们可以立即显示它们的有用性。 />


0.对于所有用例:泛型消除了代码中类型检查的需要,并从Object转换为特定类型:这是一个痛苦的 - 删除了!



1.立即替换.NET的旧数据结构



a。使用 List< SomeType> ,以及其他通用数据结构(如字典,队列,堆栈等)更高效,提供更多内部功能,并使您自己编写的代码成为可能更强类型,更易于理解和维护。



2.泛型使您能够更轻松地表达和使用复杂的复合数据结构



a。考虑这个通用代码数据结构声明:
I think as you "get to know" Generics, and have a "feeling" for how to use them, you will find them immensely useful. I also predict that your sense of what Generics can be used to do ... and to greatly simplify the coding of ... will come in "stages."

So, let me outline a few of what I consider the main "goodnesses" that Generics add to .NET, in order of what I believe is their easiness to understand, and the likelihood that their usefulness will be immediately visible to you.

0. for all use-cases: generics eliminate the need for type-checking in your code, and casting from Object to a specific Type: that's a pain-in-the-ass removed !

1. an immediate replacement for .NET's older data-structures

a. use of List<SomeType>, and other generic data structures like Dictionaries, Queues, Stacks, etc. are more efficient, offer more internal functionality, and make the code you write inherently more strongly-typed, easier to understand, and maintain.

2. Generics enable you to more easily express, and use, complex, "compound" data-structures

a. consider this generic code data-structure declaration:
var listOfListOfInt = new List<List<List<int>>>();

它简单地表达了......从内部工作的概念=> out,整数列表的集合,每个成员包含其他整数列表的集合,其中每个成员(第二级)整数列表包含其他整数列表。是的,写起来很满意:)



为了实现这一点,我们试试:我有一家汽车维修店;每周我都会写一份清单,其中包含为每次维修支付的所有款项(四舍五入到整数,即整数);每个月我都会在一个月的清单中存储四个每周清单中的每一个,每年,我将十二个月清单存储在一年清单中:我想你明白了。



现在考虑在Generics

It expresses simply the concept of ... working from the inside => out, a collection of Lists of integers, each member of which contains a collection of other Lists of integers, with each member of that (second-level) List of integers containing other Lists of integers. Yes, that's quite a mouthful to write :)

To bring that down-to-earth let's try: I have an auto-repair shop; each week I write a list containing all the money paid for each repair (rounded off to whole numbers, i.e., integers); each month I store each of the four weekly lists in a month list, and each year, I store the twelve monthly lists in a year-list: I think you get the idea.

Now consider what you would have to do to build such a data-structure before Generics

ArrayList al1 = new ArrayList();
ArrayList al2;
ArrayList al3;

for (int i = 0; i < 10; i++)
{
    al2 = new ArrayList();

    for (int j = 100; j > 90; j--)
    {
        al3 = new ArrayList();

        for (int k = 200; k < 210; k++)
        {
            al3.Add(k);
        }

        al2.Add(al3);
    }

    al1.Add(al2);
}

是的,你可能会说我在这个比较中作弊,因为你可以在.NET中使用多维数组,或者锯齿状数组(数组数组) ),那些可以是强类型的,其中ArrayLists不能是强类型的,并且只是一维的:在内部,ArrayList使用链表,当你达到条目数的限制时有内存成本一个ArrayList,它触发为ArrayList分配更多内存。并且,对于Arrays,您必须在您开始使用它们时声明它们的大小(每个维度的大小)。使用数组,您无法移除项目,也无法动态重新分配数组可容纳的项目数量!



总结一下: List< int> 为您提供强类型,灵活变化的长度(您可以添加和删除项目,无需高额开销)存储结构,该结构还提供许多其他功能,如范围访问器和操纵器等。 .NET的通用数据结构通常比旧的反向部件提供更好的性能。



3.泛型使您能够在运行时使用后期绑定。因此,如果基于用户的操作,在一个时间点需要一个整数列表,并且在另一个时间点需要一个字符串列表,您可以使用带有占位符类型声明的泛型来编写代码。用于两种情况。



如果我使用泛型编写一个简单的类:

Yes, you might say I'm cheating here in this comparison, because you can use multi-dimensional arrays in .NET., or "jagged" arrays (arrays-of-arrays), and those can be strongly-typed, where ArrayLists cannot be strongly-typed, and are only one-dimensional: internally an ArrayList uses a linked-list, and there are memory costs when you reach the limit of the number of entries in an ArrayList which triggers allocation of more memory for the ArrayList. And, with Arrays, you have to declare their size (each dimension's size) at the point you are going to start using one. With Arrays you cannot remove items, or dynamically re-allocate the number of items the Array can hold !

To sum it up: List<int> offers you a strongly-typed, flexibly variable length (you can add, and delete items, without a high overhead) storage structure that also offers many additional features, like range accessors and manipulators, etc. .NET's generic data structures usually offer better performance than their older counter-parts.

3. Generics enable you to use late-binding at run-time. So, if, based on the user's actions, at one point in time a List of integers is required, and, at another point in time a List of strings is required, you can write code using generics with "placeholder" Type declaration that can be used for both cases.

If I write a simple class using Generics:

public class GenericList<T> : List<T>
{
}

我可以这样做:

List<int> intList = new GenericList<int>();
List<string> stringList = new GenericList<string>();

for (int i = 0; i < 10; i++)
{
    intList.Add(i);
    stringList.Add(i.ToString());
}

不可否认,这是一个微不足道的例子,但我希望它能给你一些想法。



4.最后,泛型去了, imho,与Linq携手合作,以及这两个强大设施之间的协同作用,当你开始掌握它并且能够使用它时,将为你编写一个全新的维度优雅, 并且有效。



您可能会喜欢阅读Eric Lippert(他是微软最明确的大师级.NET专家之一)关于阵列的博客文章:[< a href =http://blogs.msdn.com/b/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspxtarget =_ blanktitle =New Window> ^ ]。

Admittedly, a trivial example, but I hope it gives you some ideas.

4. finally, Generics go, imho, hand-in-hand with Linq, and the synergy between those two powerful facilities, when you begin to grasp it, and become able to use it, is going to open-up a whole new dimension for you in programming "elegantly," and efficiently.

You might enjoy reading Eric Lippert's (he is one of Microsoft's most articulate guru-level .NET experts) blog entry on "Arrays:" [^].


我在第一次介绍时并没有过多地爱泛型,因为泛型在其实现代码中引入了更多层次的黑暗。但是,在编写应用程序逻辑时,泛型非常有用(代码可以更易读,因为您不需要类型转换)和代码重用。



看一下这些.net类:List<> ;, Dictionary<> ;, Queue<> ;.如果需要在应用程序中维护任意类型的列表或队列,则不需要为每个列表或类别实现一个列表类类型。字典也是如此。
I did not 'love' generics too much when first introduced as generics introduce one more level of darkness into their implementation code. But generics are of great help when coding your application logic (your code can be more readable as you'll not need type castings) and in terms of code reuse.

Take one look into these .net classes: List<>, Dictionary<>, Queue<>. If you need to maintain lists or queues of arbitrary types for usage in your application you will not need to implement one list class type for each and every one. Same happens with dictionaries.


请参阅本文以清楚了解泛型。

http://www.tutorialspoint.com/csharp/csharp_generics.htm



问候,

Mubin
please refer this article for clear understanding of Generics.
http://www.tutorialspoint.com/csharp/csharp_generics.htm

Regards,
Mubin


这篇关于泛型在C#中的实际应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆