mercredi 17 novembre 2021

Return specific type in generic method depending on enum value without Reflection or dynamic during runtime

I have a non-generic IList which i would like to cast depending on an enum value during runtime.

I can not change the type of the non-generic IList in the implementation, because it is library code.

Also i do not want to use Reflection (because it is slow) or the dynamic keyword (because it is unsafe and could lead to mistakes down the road).

In the Library Code there is following class:

public class ListView //THIS IS LIBRARY CODE AND CAN NOT BE CHANGED
{
  public IList itemsSource { get; set; }
}

Then in my CustomListView class which inherits from ListView i want to cast the itemsSource to the appropiate class depending on ItemType.

Another limitation is that CustomListView can not be generic (dictated by the library we use)

public class CustomListView : ListView
{
    public dynamic GetItems()
    {
        switch (ItemType)
        {
            case ItemType.A:
              return itemsSource.Cast<A>().ToList();
            case ItemType.B:
              return itemsSource.Cast<B>().ToList();
            default:
              throw new InvalidOperationException("Not supported");
        }
    }
}

But i want it to directly return the correct type instead of using dynamic.

Something like (the code below does not work!):

public IList<T> GetItems(ItemType itemType) //The type of T should change depending on what i return
{
    switch (ItemType)
    {
        case ItemType.A:
          return itemsSource.Cast<A>().ToList();
        case ItemType.B:
          return itemsSource.Cast<B>().ToList();
        default:
          throw new InvalidOperationException("Not supported");
    }
}

How would i implement that?





Aucun commentaire:

Enregistrer un commentaire