使用列表< T>在C#(泛型) [英] Using List<T> in C# (Generics)
问题描述
这是一个非常基本的问题,但我从来没有深入研究仿制药之前,我发现自己在需要使用它。不幸的是我没有时间,现在要经过任何教程,我发现相关的问题至今没有什么人可以称之为基本的答案,所以我们去:
让我们说我有以下几点:
列表< MyClass1的> list1的= getListType1();
名单,LT; MyClass2>列表2 = getListType2();
如果(someCondition)
的MyMethod(list1的);
,否则
的MyMethod(列表2);
当然,
无效的MyMethod(列表< T>名单){
//做的东西
}
好吧,我想这将是这个简单,但显然事实并非如此。 VS警告我说,
有关方法的MyMethod类型参数(System.Collections.Generic.List)不能从使用推断
块引用>
如果我反正编译它,我得到一个
类型或命名空间名称'T'找不到
块引用>
错误。
在很多答案,我发现,我读,我必须声明一下
T
是,这是有道理的,但我不能完全掌握如何在这样一个简单的情况下做到这一点。当然,这些问题的答案创建在我的脑海,甚至更多的问题,但现在我只是想什么我做错了(除了不学习仿制药),以及如何作出正确选择。
<解释DIV CLASS =h2_lin>解决方案
您需要声明 T
对方法,那么C#可以识别方法接收的类型。试试这个:
无效的MyMethod< T>(列表< T>名单){
//做的东西
}
然后做称呼它:
如果(someCondition)
的MyMethod(list1的);
,否则
的MyMethod(列表2);
您可以使它更加严格,如果你要的所有类传递到方法都有一个共同的基类:
无效的MyMethod< T>(列表< T>清单),其中T:MyClassBase
That's a pretty elementary question, but I have never delved into generics before and I found myself in the need to use it. Unfortunately I don't have the time right now to go through any tutorials and the answers I found to related questions so far aren't what one could call basic, so there we go:
Let's say I have the following:
List<MyClass1> list1 = getListType1();
List<MyClass2> list2 = getListType2();
if (someCondition)
MyMethod(list1);
else
MyMethod(list2);
And of course
void MyMethod(List<T> list){
//Do stuff
}
Well, I thought it would be this simple, but apparently it is not. VS warns me that
The type arguments for method MyMethod(System.Collections.Generic.List) cannot be inferred from the usage
and if I compile it anyway, I get a
The type or namespace name 'T' could not be found
error.
In the many answers I found, I read that I have to declare what T
is, which makes sense, but I couldn't quite grasp how to do so in such a simplistic scenario. Of course, those answers created even more questions in my mind, but right now I just want an explanation of what I'm doing wrong (besides not studying generics) and how to make it right.
You need to declare T
against the method, then C# can identify the type the method is receiving. Try this:
void MyMethod<T>(List<T> list){
//Do stuff
}
Then call it by doing:
if (someCondition)
MyMethod(list1);
else
MyMethod(list2);
You can make it even stricter, if all classes you are going to pass to the method share a common base class:
void MyMethod<T>(List<T> list) where T : MyClassBase
这篇关于使用列表< T>在C#(泛型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!