0

I have a main class where I am looping through each internal property in my cleats class property. Each internal property in my cleats class is of type BeltProperty (another class that contains information like value and id's).

private ObservableCollection<Cleats> _Cleats = new ObservableCollection<Cleats>();
    /// <summary>
    /// Cleats
    /// </summary>
    public ObservableCollection<Cleats> Cleats { get { return _Cleats; } }

foreach (PropertyInfo prop in typeof(Cleats)
    .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic))
{
    BeltProperty bp = new BeltProperty();
    bp = (BeltProperty)Cleats[Configurator_2016.Cleats.SelectedConfigurationIndex]
        .GetType().GetProperty(prop.Name, BindingFlags.Instance | BindingFlags.NonPublic)
        .GetValue(this, null);
    //rest of the code...
}

On the first BeltProperty it finds it throws a System.Reflection.TargetException. I want to know if there is another/better way to get the property from my cleats class. Thanks in advance for any help or advice.

andrewvb
  • 17
  • 6
  • Probably it's because of your send `this` as the target parameter to the `GetValue` method. but your code is not clear. What is `Cleats.GetProperties` ? what is `Cleats[Configurator_2016.Cleats.SelectedConfigurationIndex]`? be sure to post all relevant code – Ofir Winegarten Jun 02 '17 at 14:25
  • I tried using Cleats instead of this in getValue and still has the same result. – andrewvb Jun 02 '17 at 14:39
  • @andrewvb what's the type of `Cleats`? Method `GetProperties` is strange, at least it's not clear where it is located. – Alex Sikilinda Jun 02 '17 at 14:45
  • Cleats is of type Cleats class. Sorry I know its a bit confusing to explain. GetProperties is a method in the public abstract class type : MemberInfo, _Type, IReflect. Also Cleats.GetProperties should be typeof(Cleats).GetProperties. – andrewvb Jun 02 '17 at 14:52

1 Answers1

0

Well first i would choose better names for the classes and instances.
ObservableCollection<Cleats> Cleats is not straight forward.

The issue you are having is because of this parameter in .GetValue(this, null);

This parameter should be the instance that you are trying to read the property from.

The whole code could look like this:

foreach (PropertyInfo prop in typeof(Cleats)
    .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic))
{
    var bp = (BeltProperty)prop.GetValue(Cleats[Configurator_2016.Cleats.SelectedConfigurationIndex])
}
Ofir Winegarten
  • 9,215
  • 2
  • 21
  • 27
  • 1
    Thanks, you were right, I had the GetValue contents wrong and I had to specify the correct object. – andrewvb Jun 02 '17 at 15:31