C#C
C#3y ago
Pacrombie

❔ ✅ Reflection to get all Properties of a certain type

I have this in a class:
List<KeyCode> keyCodeProperties = typeof(SettingsData)
                .GetProperties(System.Reflection.BindingFlags.Public)
                .Select(property => property.GetValue(GameManager.Instance.Settings))
                .ToList();

And this in the referenced Settings object:
    public float MouseSens
    {
        get
        {
            return _mouseSens;
        }
        set
        {
            _mouseSens = value;
        }
    }
    public KeyCode PrimaryFireKey
    {
        get
        {
            return _primaryFireKey;
        }
        set
        {
            _primaryFireKey = value;
        }
    }
    public KeyCode AltFireKey
    {
        get
        {
            return _altFireKey;
        }
        set
        {
            _altFireKey = value;
        }
    }
...

The first block of code I sent does not compile because all the crap after the equals sign returns a list of objects, and I need a list of
KeyCode
s. I've hardly ever used Reflection and I'm just a little lost. I know my code as it stands (if I were to change my list to a
List<object>
gets the values of all properties in my given class), but I just want the
KeyCode
properties in a List. Any help would be appreciated. I'm starting to think it would just be better to have them in a Dictionary in my Settings class since the names of the properties do matter (I could use Dictionary keys). Anyways, thank u in advance :)
Was this page helpful?