Home > Backend Development > C++ > How Can I Achieve Polymorphism with Open Generic Types in C#?

How Can I Achieve Polymorphism with Open Generic Types in C#?

Mary-Kate Olsen
Release: 2025-01-11 06:46:41
Original
205 people have browsed it

How Can I Achieve Polymorphism with Open Generic Types in C#?

Polymorphism using open generic types in C#

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.

Question

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>
Copy after login

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.

Solution

C# does not support true polymorphism for open generic types. To overcome this problem, you have several options:

  1. Create a list of objects:

    <code class="language-csharp"> List<object> dataCollection = new List<object>();
    
     dataCollection.Add(new DecimalData());
     dataCollection.Add(new StringData());</code>
    Copy after login

    However, this approach loses type safety and requires explicit conversion when accessing the data.

  2. 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>
    Copy after login

    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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template