public partial class BaseClass : Form
{
private bool myBaseBool;
private NewClass newClass = new NewClass();
public BaseClass()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
ChildClass childC = new ChildClass();
newClass.NewClassInt = 50;
childC.RunTest();
bool testBool = myBaseBool;
}
private void DoSomething(int number, string text)
{
int i = number;
string s = text;
}
}
public class NewClass
{
public int NewClassInt = 10;
}
public class ChildClass : BaseClass
{
public void RunTest()
{
//Test one setting base class private testBool ------ Working
var myObj = this;
var myField1 = typeof(ChildClass).BaseType.GetField("myBaseBool", BindingFlags.Instance | BindingFlags.NonPublic);
myField1.SetValue(myObj, true);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Test two invoking base class private method -------- Working
object[] ob = {1, "test"};
typeof(ChildClass).BaseType.GetMethod("DoSomething", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(myObj, ob);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Test three get value from base class instance of NewClass -------- Not Working
var myField2 = typeof(ChildClass).BaseType.GetField("newClass", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
var value = ((NewClass) myField2.GetValue(myObj)).NewClassInt;//Always gets the default value of NewClass
}
}
}
Why is test three returning the default NewClassInt value and not returning the base class instance NewClassInt value?
Please no "why do you want to do that questions" I seen enough of them when it comes to the subject Reflection. All I'm doing is trying to learn.
Aucun commentaire:
Enregistrer un commentaire