Home >Backend Development >C++ >How to Create a List of Open Generic Types (Class) in C#?
How to create a list of open generic types (Class
In programming, you may encounter scenarios where you need to process multiple types of data in a collection. In this case, generics can provide a flexible solution. However, using open generic types, such as List, sometimes results in compiler errors.
Suppose you have a class Data
<code class="language-c#">List<Data> dataCollection = new List<Data>();</code>
However, this code will not compile because the compiler will complain that the generic type "Data" requires a type parameter. This is because, for open generic types, the compiler cannot infer the type parameters when constructing the list.
Understanding open and closed generic types
To solve this problem, it is important to understand the difference between open and closed generic types. In the case of List, it represents an open generic type, which means that the type parameter T remains unspecified. On the other hand, a closed generic type specifies type parameters, such as List> or List>.
Create a list of closed generic type
To create a list of a closed generic type, you need to specify the type parameters when constructing the list. For example:
<code class="language-c#">List<Data<string>> stringDataCollection = new List<Data<string>>(); List<Data<decimal>> decimalDataCollection = new List<Data<decimal>>();</code>
These lists can now accept instances of StringData and DecimalData respectively.
Limitations of Open Generic Type Polymorphism
Unfortunately, in C#, there is no direct mechanism to achieve true polymorphism of open generic types. This means that you cannot create a list like List> and store different enclosing types in it, such as Data
Alternative methods
If you need to maintain a collection containing objects of different types, you may consider the following alternatives:
The above is the detailed content of How to Create a List of Open Generic Types (Class) in C#?. For more information, please follow other related articles on the PHP Chinese website!