gpt4 book ai didi

c# - 在 C# 中使用 List(泛型)

转载 作者:IT王子 更新时间:2023-10-29 04:23:06 25 4
gpt4 key购买 nike

这是一个非常基本的问题,但我以前从未深入研究过泛型,但我发现自己需要使用它。不幸的是,我现在没有时间浏览任何教程,而且到目前为止我找到的相关问题的答案都不是基本的答案,所以我们开始吧:

假设我有以下内容:

List<MyClass1> list1 = getListType1();
List<MyClass2> list2 = getListType2();

if (someCondition)
MyMethod(list1);
else
MyMethod(list2);

当然

void MyMethod(List<T> list){
//Do stuff
}

好吧,我以为它会这么简单,但显然不是。 VS 警告我

The type arguments for method MyMethod(System.Collections.Generic.List) cannot be inferred from the usage

如果我仍然编译它,我会得到一个

The type or namespace name 'T' could not be found

错误。

在我找到的许多答案中,我读到我必须声明 T 是什么,这是有道理的,但我不太明白在这种简单的情况下如何这样做。当然,这些答案在我脑海中产生了更多问题,但现在我只想解释我做错了什么(除了没有研究泛型)以及如何改正。

最佳答案

您需要针对该方法声明T,然后C# 可以识别该方法接收的类型。试试这个:

void MyMethod<T>(List<T> list){
//Do stuff
}

然后调用它:

if (someCondition)
MyMethod(list1);
else
MyMethod(list2);

如果要传递给该方法的所有类都共享一个公共(public)基类,则可以使其更严格:

void MyMethod<T>(List<T> list) where T : MyClassBase

关于c# - 在 C# 中使用 List<T>(泛型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19138991/

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