In C#, you can create a class with generic type parameters. However, is it possible to create a list that contains multiple different instances of this generic class with different type parameters?
Let us consider the following example:
<code class="language-csharp">public class Metadata<DataType> where DataType : struct { private DataType mDataType; }</code>
Here, we have a generic class Metadata
that can be used for different value types. Now, let's say we want to create a list of these Metadata
objects, which have different types. Can we do it?
<code class="language-csharp">List<Metadata<DataType>> metadataObjects; // 错误:DataType 未定义 metadataObjects.Add(new Metadata<int>()); metadataObjects.Add(new Metadata<bool>()); metadataObjects.Add(new Metadata<double>());</code>
Unfortunately, this is not possible in C# because the generic type parameter of a list must be the same for all elements. To overcome this limitation, inheritance and abstract classes can be used.
<code class="language-csharp">public abstract class MetadataBase { } // 继承抽象 MetadataBase 类 public class Metadata<DataType> : MetadataBase where DataType : struct { private DataType mDataType; }</code>
Now you can create a list of abstract base classes MetadataBase
. This allows you to add different types of Metadata
objects to the list:
<code class="language-csharp">List<MetadataBase> metadataObjects = new List<MetadataBase>(); metadataObjects.Add(new Metadata<int>()); metadataObjects.Add(new Metadata<bool>()); metadataObjects.Add(new Metadata<double>());</code>
By using an abstract base class, we successfully create a list that can hold instances of different types Metadata
. It should be noted that type conversion is required when accessing the mDataType
attribute of an element in the list, because MetadataBase
does not contain this attribute. This needs to be handled on a case-by-case basis, such as using dynamic
types or the is
operator for type checking and conversion.
The above is the detailed content of Can a C# List Hold Multiple Generic Class Instances with Different Type Parameters?. For more information, please follow other related articles on the PHP Chinese website!