samedi 9 avril 2016

c# - Set private field in inherit class

Okay so I have a program that contains multiple classes some of wich inherit eachother. The basic layout looks like this:

public class Foo2
{
    public string junk1 = "bleh"; // Not useful
}

public class Foo1 : Foo2
{
    private int num = 2; // I want to access this
    private string junk2 = "yo";
}

public class Foo : Foo1
{
    public string junk3 = "no";
}

Now in another I have as follows:

public class access // I used Reflection
{
    private Foo2 test = new Foo2(); // The only thing important here is that test is Foo2

    private void try1() // This was my frist attempt(It didn't work)
    {
        Foo tst = (Foo)test;
        tst.GetType().GetField("num", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(tst, 5);
    }

    private void try2() // Second attempt also didn't work
    {
        Foo1 tst = (Foo1)test;
        tst.GetType().GetField("num", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(tst, 5);
    }
}

None of the methods I tried worked. Please help

Oh and sorry for any incorrect spelling in the code I had to use notepad

Thanks





Aucun commentaire:

Enregistrer un commentaire