samedi 26 novembre 2016

C#, Easiest way to modify private objects from other classes

What would be the easiest way to modify a privately declared object from inside another class? I heard reflection could possibly do it. The basic scenario below.

Object class

public class item1{

    private int num;

    public int get(){
        return num;
    }

    public void set(int newnum){
        num = newnum;
    }
}

Unmodified class

public class item2(){

    private item1 obj = new item1;

    static void Main(string[] args){
        obj.set(1);
    }

    public int getFinal(){
        return obj.get();
    }
}

Our Class

public class item3(){

    private item1 obj = new item1;
    //stuff here

    static void changeObj(){
        obj.set(2);
    }
}

Assuming we already have a way to call the classes/functions in appropriate order, what do we add in item3 in order to make item2.getFinal() return 2?





Aucun commentaire:

Enregistrer un commentaire