gpt4 book ai didi

c# - 对泛型和列表的困惑

转载 作者:行者123 更新时间:2023-11-30 16:15:36 24 4
gpt4 key购买 nike

我正在学习 C# 中的泛型和列表,但我对这两个主题的语法和用法感到非常困惑。 MSDN我看过了,但看完后我更糊涂了。

我很困惑为什么有时你可以拥有 public T variable name; <-- 类型变量 T ???

然后你可以以某种方式拥有List<T>List<double> List<int> <- 为什么我们需要 <>突然之间,这个名为 List 的新类是什么?如果T是不同于 int 或 double 的新类型或 string那么这个新类型有什么值(value)呢?为什么我们可以放<double> ?这是两个不同的概念吗? (List<T>List<double> )现在他们甚至使用类型为 T 的数组....此类型TList有两件事真的让我感到困惑。 List 的目的/用途是什么?它与 <T> 有何不同? ?

最佳答案

T只是一个类型的占位符。例如:

public void PrintType<T>(T source)
{
Console.WriteLine(source.GetType());
}

int number = 23;
string text = "Hello";

PrintType(number);
PrintType(text);

这里我们有一个接受 T source 的通用函数范围。该参数的类型可以是任何类型,因此我们使用 T标记那个。你可以使用任何字母,但是 T似乎最常使用。

当你有一个通用列表时 List<int>例如,您要声明列表将包含的类型,在本例中为 integers .这就是为什么你需要 <> , 这是您指定类型的地方。

List<>不创建泛型类型,它是一个集合对象,可以存储 T 类型的对象(假设您将列表声明为 List<T>,例如 List<int>List<string> 等)。在引擎盖下,List<>确实使用数组,但不要太担心细节。

编辑:

作为引用,这里是 List<> 的一些简化的、部分的代码我使用 dotPeek 获得的

public class List<T>
{
private static readonly T[] _emptyArray = new T[0];
private const int _defaultCapacity = 4;
private T[] _items;
private int _size;
private int _version;

public void Add(T item)
{
if (this._size == this._items.Length)
this.EnsureCapacity(this._size + 1);

this._items[this._size++] = item;
}

private void EnsureCapacity(int min)
{
if (this._items.Length >= min)
return;
int num = this._items.Length == 0 ? 4 : this._items.Length * 2;
if (num < min)
num = min;
this.Capacity = num;
}

public int Capacity
{
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get
{
return this._items.Length;
}
set
{
if (value < this._size)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
if (value == this._items.Length)
return;
if (value > 0)
{
T[] objArray = new T[value];
if (this._size > 0)
Array.Copy((Array) this._items, 0, (Array) objArray, 0, this._size);
this._items = objArray;
}
else
this._items = List<T>._emptyArray;
}
}
}

如您所见,List<>是一个使用数组的包装类,在本例中是一个通用数组。我强烈建议获取 dotPeek 或其他类似工具,并查看类似 List<> 的内容,这样您就可以更好地了解它们的工作原理。

关于c# - 对泛型和列表的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19383130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com