lundi 1 octobre 2018

C# Generically using KeyValuePair with different value types

I am using reflection to iterate over an enumerable object, and collect all data of a certain interface type.

In the case when the object is a dictionary, I also want to do something with string Key "Name".

public interface IDisplayable
{
}

...

foreach (var item in enumerable)
{
  var itemType = item.GetType();

  if (item is KeyValuePair<string, IDisplayable> keyValue)
  {
      string name = keyValue.Key;
      ///do something with the name here
  }

  var displayableDatas = itemType.GetProperties().Select(x => x.GetValue(item)).OfType<IDisplayable>();

  ///do something with all collected interfaces
}

The problem I am facing is that it will never enter the if statement, even when the object is of the interface type IDisplayable.

It does work if I directly put in the class that extends the interface.

What is a good workaround?

The annoying thing is KeyValuePair does not implement any interface that I can use.





Aucun commentaire:

Enregistrer un commentaire