jeudi 8 octobre 2015

OfType to access Generic Parent class

I have the following classes / interfaces:

  • public interface IUiCommand
  • public class StartLandenSynchronisatieUiCommand : IUiCommand; public class SyncGeldverstrekkersUiCommand : IUiCommand; etc.
  • public class RibbonButtonAggregateViewModel<TCommand> : RibbonButtonViewModel<TCommand> where TCommand : IUiCommand
  • public abstract class RibbonButtonViewModel<TCommand> : ResizableRibbonItem where TCommand : IUiCommand
  • Some other implemented classes of RibbonButtonViewModel.

RibbonButtonViewModel contains a property KeyTip.

In a UnitTest I'm working on I have a list containing two items: RibbonButtonAggregateViewModel<StartLandenSynchronisatieUiCommand> and RibbonButtonAggregateViewModel<SynGeldverstrekkersUiCommand (this is just an example, I have a lot more lists with different IUiCommands or other implemented classes of RibbonButtonViewModel).

What I want to have is this list as RibbonButtonViewModels so I can access their KeyTip-property in a for-each.

Based on this SO question & answer, I am able to filter the list correctly, so I still have the list of two:

// `items` is the list containing the two RibbonButtonAggregateViewModels
var correctItems = items.Where(x =>
    {
        if (!x.GetType().IsGenericType) return false;
        var baseType = x.GetType().BaseType;
        if (baseType == null || !baseType.IsGenericType) return false;
        return baseType.GetGenericTypeDefinition() == typeof (RibbonButtonViewModel<>);
    })
    .ToList();

Even though I filter the list correctly and get both items when they are RibbonButtonViewModels with IUiCommand as generic type, I don't get a result of RibbonButtonViewModels to access the KeyTip. I tried adding either of the following two between the Where and ToList, but both doesn't work:

  • .OfType<RibbonButtonViewModel<IUiCommand>>() -> Results in empty list
  • .Select(x => x as RibbonButtonViewModel<IUiCommand>) -> Results in list containing two null

So, how should I get a list of RibbonButtonViewModel to access the KeyTip-property when I have the child items-list. (PS: Doesn't have to be RibbonButtonAggregateViewModel in particular, any implemented class with the RibbonButtonViewModel as base is fine, as long as the list is returned as RibbonButtonViewModels so I can access the KeyTip-property.





Aucun commentaire:

Enregistrer un commentaire