简体   繁体   中英

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);
 }

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);
}

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM