dimanche 9 juin 2019

Accessing private field in distant parent class with reflection returns null

I am trying access the private field of _id in Xamarin.Forms.Element. Which is a distant parent of Xamarin.Forms.Label.

void Handle_Clicked(object sender, System.EventArgs e)
{
    var label = new Label() { Text = "text" };
    var element = GetElement(label.GetType());
    var field = element.GetField("_id", BindingFlags.Instance | BindingFlags.NonPublic);
    var runtimeFields = element.GetRuntimeFields();
    var runtimeField = runtimeFields.First(f => f.Name == "_id");

    Console.WriteLine("label: " + field.GetValue(label));
    Console.WriteLine("runtime label: " + runtimeField.GetValue(label));
}

I am getting the Element base type with this method

private Type GetElement(Type type)
{
    if (type.Name != "Element")
    {
        return GetElement(type.BaseType);
    }
    return type;
}

I successfully get _id field and runtimeField - but calling GetValue(label) I get null. When setting a breakpoint and inspecting I can see that the label has a value for _id in Xamarin.Forms.Element BaseType. But that value does not write to console. Why?





Aucun commentaire:

Enregistrer un commentaire