lundi 2 juillet 2018

Overriding an internal get-only property from a base class

I have this class, defined in one of .NET's framework assemblies:

public class ExternalClass
{    
   internal double DesiredProperty => 1.0;    
}

I derive from ExternalClass and would like to either override or somehow intercept calls to that property. I'm aware that this can get very hacky, but it's really only for a proof-of-concept.

I tried the straightforward way with reflection, but haven't had any luck:

 private void DoEvilStuff()
    {
        var prop = typeof(ExternalClass).GetProperty("DesiredProperty", BindingFlags.Instance | BindingFlags.NonPublic);

        // Exception: Property has no setter
        prop.SetValue(this, 5);
    }

From another answer:

private void DoEvilStuff()
{
    var prop = typeof(ExternalClass).GetField("<DesiredProperty>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);

    // fails, prop is null:
    prop.SetValue(this, 5);
}

Is there a way to do this with reflection, or any other method with reasonable small effort? I can (properly) work around this for my actual problem, so a "No" is really an acceptable answer, but I'm curious if this would be possible.





Aucun commentaire:

Enregistrer un commentaire