I just started digging through C# being a java user. I run into a problem, declaring a list of generic raw type. Consider class A<T>
and B : A<String>
, C : A<Int16>
. Now I want to declare something like List<A> list
. I face a problem at this kind of declaration, getting a " generic type argument requires 1 argument ". Is there any way I could do something like that? Or there are some other patterns in C# to use?
When using a generic type you have to specify the type parameter. In this case to declare a List
of A
you have to specify T
. For example:
List<A<int>> list = new List<A<int>>();
or seeing as B
and C
both derive from A
and explicitly specify T
, then you can have:
List<B> list = new List<B>();
List<C> list = new List<C>();
UPDATE #1
Before using the following example I must admit I've not given it much thought on just how useful/practical using a
List
ofdynamic
would be or what issues may present themselves, but just thought I would offer the suggestion.
public class A<T>
{
public T Value { get; set; }
}
List<A<dynamic>> list = new List<A<dynamic>>();
list.Add(new A<dynamic> { Value = "Hello World" });
list.Add(new A<dynamic> { Value = 100 });
foreach(A<dynamic> item in list)
{
Console.WriteLine(item.Value);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.