7

I am currently trying to convert a Xamarin.iOS app library to a PCL. I have this code that will not compile:

    private void SetPrivateField<T>(object item, string fieldName, object value) {
        typeof(T).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic)
            .SetValue(item, value);
    }

As you can see I am trying to set a private field for a type. Is there another way?

EDIT This compiles. Will it do the same thing?

 private void SetPrivateField<T>(object item, string fieldName, object value) {
      typeof(T).GetRuntimeField(fieldName).SetValue(item,value);
 }
Chris Kooken
  • 32,730
  • 15
  • 85
  • 123

2 Answers2

6

This ended up being the correct code.

private void SetPrivateField<T>(object item, string fieldName, object value) {
    typeof(T).GetTypeInfo().GetDeclaredField(fieldName).SetValue(item,value);
}
Chris Kooken
  • 32,730
  • 15
  • 85
  • 123
2

The reflection APIs in Portable Class Libraries targeting newer platforms are different. See the following links for some info on why we did this and how to use the new APIs:

Community
  • 1
  • 1
Daniel Plaisted
  • 16,674
  • 4
  • 44
  • 56