Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Portable Class Library Reflection GetField

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);
 }
like image 635
Chris Kooken Avatar asked Dec 10 '13 22:12

Chris Kooken


2 Answers

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);
}
like image 199
Chris Kooken Avatar answered Oct 12 '22 23:10

Chris Kooken


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:

  • Portable Class library and reflection
  • Why can't I call Delegate.CreateDelegate in my Portable Class Library?
  • Blog post: Evolving the Reflection API
like image 43
Daniel Plaisted Avatar answered Oct 12 '22 23:10

Daniel Plaisted