Cast a parent class to child
It would seem my problem should have a nice simple solution, but I just can't find the syntax for it. First here's my code (simplified for the purpose of this problem):
Code:
public class Class1 {
public int myVar = 1;
private void LinkMe() {
Test.Instance.LinkMe(this);
}
}
public class Class2 {
public int myVar = 2;
private void LinkMe() {
Test.Instance.LinkMe(this);
}
}
public class Test { // this is a singleton
private static Test instance;
public void LinkMe(object obj) {
Debug.Log(obj.GetType()); // Outputs "Class1", "Class2" ...
Debug.Log(obj.myVar1); // gives error: "Type `object' does not contain a definition for `myVar'
}
public static Test Instance {
get {
if (instance == null) {
instance = new Test();
}
return instance;
}
}
}
What I really want here is to pass different classes (in my example I only made Class1 and Class2) to one method in Test. The classes all share one variable called myVar which I want to access in Test. Since the argument of LinkMe method must have only one type, I use a parent class (namely object) of the classes calling the method.
Now, in Test it seems LinkMe knows which type of class it gets passed, since that is what GetType() outputs. But when assuming this and trying to access myVar it suddenly acts as it was just an object and not what GetType() said it was.
All I really wanna do here is get access to that variable myVar, but I can't find the right syntax for it. I tried something like this:
Code:
Type realType = obj.GetType();
realType myClass = (realType) obj;
myClass.myVar = 2;
..which of course doesn't work. So is there a way to do this simple?
Note: I want to solve this without extending Class1, Class2, etc and without having to use manually the names of Class1, Class2, etc.