简体   繁体   English

Raw通用类型C#列表

[英]List of Raw generic type c#

I just started digging through C# being a java user. 我刚刚开始通过C#作为Java用户进行挖掘。 I run into a problem, declaring a list of generic raw type. 我遇到一个问题,声明了一个通用原始类型的列表。 Consider class A<T> and B : A<String> , C : A<Int16> . 考虑类A<T>B : A<String>C : A<Int16> Now I want to declare something like List<A> list . 现在,我想声明类似List<A> list I face a problem at this kind of declaration, getting a " generic type argument requires 1 argument ". 我在这种声明时遇到问题,获取“ 泛型类型参数需要1个参数 ”。 Is there any way I could do something like that? 有什么办法可以做这样的事情吗? Or there are some other patterns in C# to use? 还是在C#中还有其他一些模式可以使用?

When using a generic type you have to specify the type parameter. 使用泛型类型时,必须指定type参数。 In this case to declare a List of A you have to specify T . 在这种情况下,要声明AList ,必须指定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: 或者看到BC都从A派生并显式指定T ,那么您可以:

List<B> list = new List<B>();
List<C> list = new List<C>();

UPDATE #1 更新1

Before using the following example I must admit I've not given it much thought on just how useful/practical using a List of dynamic would be or what issues may present themselves, but just thought I would offer the suggestion. 在使用以下示例之前,我必须承认,我对使用dynamic List的实用性/实用性或可能出现的问题没有多加考虑,而只是想我会提出建议。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM