Lists in C# store multiple generic types
Generic types in C# provide a powerful mechanism for creating classes and methods that can operate on various data types. However, a common problem often arises when trying to use multiple generic types in a list.
Consider the following example:
<code class="language-csharp">public class Metadata<DataType> where DataType : struct { private DataType mDataType; } List<Metadata<DataType>> metadataObjects; //错误: DataType 未定义 metadataObjects.Add(new Metadata<int>()); metadataObjects.Add(new Metadata<bool>()); metadataObjects.Add(new Metadata<double>());</code>
The goal here is to create a list containing Metadata objects of different data types. However, the Metadata<DataType>
constraint on the where
class restricts the generic type DataType
to a value type. This means metadataObjects
that each item in the list must be of the same generic type, so it is not possible to add objects of different types.
To overcome this limitation, one way is to introduce an abstract base class for Metadata
as follows:
<code class="language-csharp">public abstract class Metadata { } // 继承抽象 Metadata 类 public class Metadata<DataType> : Metadata where DataType : struct { private DataType mDataType; }</code>
By creating an abstract base class Metadata
, a generic class Metadata<DataType>
can now extend this base class. This allows us to have a list of Metadata
objects where each item can be a different generic type.
The modified code is as follows:
<code class="language-csharp">List<Metadata> metadataObjects = new List<Metadata>(); metadataObjects.Add(new Metadata<int>()); metadataObjects.Add(new Metadata<bool>()); metadataObjects.Add(new Metadata<double>());</code>
Now metadataObjects
lists can hold objects of different value types, effectively achieving the goal of having multiple generic types in a list. It should be noted that type conversion is required when accessing mDataType
attributes, because the Metadata
base class does not know the specific DataType
.
The above is the detailed content of How Can I Store Multiple Generic Types in a Single List in C#?. For more information, please follow other related articles on the PHP Chinese website!