vendredi 2 mars 2018

How to get static properties from static class using reflection

I've got a static class with static getters.

public static class Cars
{
   public static KeyValuePair<Guid, string> Acura
   {
       get { return new KeyValuePair<Guid, string>(new Guid("MMMMMMMM-509B-477A-ADB1-5CD014B41001"), "Acura"); }
   }
   public static KeyValuePair<Guid, string> AlfaRomeo
   {
      get { return new KeyValuePair<Guid, string>(new Guid("MMMMMMMM-509B-477A-ADB1-5CD014B41002"), "Alfa Romeo"); }
   }
   // etc.
}

I need to retrieve all the static properties from this static class and do something with each KeyValuePair. But the following throws a System.FormatException at runtime saying that it could not find recognizable digits

Type type = typeof(Cars);
foreach(var manufacturer in type.GetProperties())
{
    if(manufacturer.PropertyType == typeof(KeyValuePair<Guid, string>))
    {
        var v = manufacturer.GetValue(null, null); //this does not work
        // How to get the KeyValuePair<Guid, string>? 
    }
}

How to get each KeyValuePair?





Aucun commentaire:

Enregistrer un commentaire