When dealing with generic code, you usually encounter scenarios where you need to operate various types of data. However, C#'s generic polymorphism has limitations when it comes to dealing with open generic types.
Consider the following code:
<code class="language-csharp">public abstract class Data<T> { } public class StringData : Data<string> { } public class DecimalData : Data<decimal> { } List<Data<T>> dataCollection = new List<Data<T>>(); // 错误:缺少类型参数 dataCollection.Add(new DecimalData()); dataCollection.Add(new StringData());</code>
In this example, you want to create a list that can hold instances of different Data subtypes. However, the last line fails with a compiler error because open generic types (e.g. Data) require type parameters to be specified.
C# does not support true polymorphism for open generic types. To overcome this problem, you have several options:
Create a list of objects:
<code class="language-csharp"> List<object> dataCollection = new List<object>(); dataCollection.Add(new DecimalData()); dataCollection.Add(new StringData());</code>
However, this approach loses type safety and requires explicit conversion when accessing the data.
Use non-generic interfaces or abstract classes:
<code class="language-csharp"> public interface IData { void SomeMethod(); } public abstract class Data<T> : IData { public void SomeMethod() { } } List<IData> dataCollection = new List<IData>(); dataCollection.Add(new DecimalData()); dataCollection.Add(new StringData());</code>
This allows non-generic operations on list elements, at the expense of some genericity and type safety.
It is important to understand the limitations and trade-offs of using open generic types in C# and choose the solution that best suits your specific needs.
The above is the detailed content of How Can I Achieve Polymorphism with Open Generic Types in C#?. For more information, please follow other related articles on the PHP Chinese website!