本文介绍了什么是"< >"在C#语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习了C#的基础知识,但还没有遇到什么,这是一个很好的解释:

I have been learning about the basics of C# but haven't come across a good explanation of what this is:

var l = new List<string>();

我不知道是什么&LT;字符串&GT; 正在做,或者如果它是列表正在做魔术。我也看到了物体的&LT中抛出; &GT; 标签

I don't know what the <string> is doing or if it's the List that is doing the magic. I have also seen objects been thrown within the < > tags.

有人可以解释这对我来说有例子,好吗?

Can someone explain this to me with examples, please?

推荐答案

这是C#泛型的语法。

的基本概念是,它可以让你用一个类型占位符,并在编译时代替实际的真正类型

The basic concept is that it allows you to use a Type placeholder and substitute the actual real type in at compile time.

例如,旧的方式:

ArrayList foos = new Arraylist();
foos.Add("Test");

曾通过ArrayList的商店System.Objects列表(对所有事情的.NET基本类型)。

worked by making ArrayList store a list of System.Objects (The base type for all things .NET).

因此​​,添加或从列表中检索对象时,将CLR将不得不将它转换为对象,基本上是真的发生是这样的:

So, when adding or retrieving an object from the list, The CLR would have to cast it to object, basically what really happens is this:

foos.Add("Test" as System.Object);
string s = foos[1] as String.

这导致从铸造性能损失,并且其还不安全的,因为我可以做到这一点:

This causes a performance penalty from the casting, and its also unsafe because I can do this:

ArrayList listOfStrings = new ArrayList();
listOfStrings.Add(1);
listOfStrings.Add("Test");

这将编译就好了,即使我把一个整数listOfStrings。

This will compile just fine, even though I put an integer in listOfStrings.

泛型改变了这一切,现在使用泛型,我可以声明一下,键入我的收藏预计,:

Generics changed all of this, now using Generics I can declare what Type my collection expects:

List<int> listOfIntegers = new List<int>();
List<String> listOfStrings = new List<String>();

listOfIntegers.add(1);

// Compile time error.
listOfIntegers.add("test");

这提供了编译时类型安全,并避免了昂贵的铸造业务。

This provides compile-time type safety, as well as avoids expensive casting operations.

您可以利用这个问题的方法是pretty的简单,但也有一些先进的边缘情况。其基本理念是让你的类的类型无关通过使用一种类型的占位符,例如,如果我想创建一个通用的补充两点类。

The way you leverage this is pretty simple, though there are some advanced edge cases. The basic concept is to make your class type agnostic by using a type placeholder, for example, if I wanted to create a generic "Add Two Things" class.

public class Adder<T>
{
   public T AddTwoThings(T t1, T t2)
   {
       return t1 + t2;
   }
}

Adder<String> stringAdder = new Adder<String>();
Console.Writeline(stringAdder.AddTwoThings("Test,"123"));

Adder<int> intAdder = new Adder<int>();
Console.Writeline(intAdder.AddTwoThings(2,2));

有关更详细的解释,仿制药的,我无法通过C#建议足够的书CLR。

For a much more detailed explanation of generics, I can't recommend enough the book CLR via C#.

这篇关于什么是&QUOT;&LT; &GT;&QUOT;在C#语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:02