How can I use a non static variable in another class? Here's my problem:
public class class1
{
int a;
public int alpha{ get { return a; } }
public void Method1()//method gets called...
{
a++;
}
public class class2
{
// Here initializing class2 variable as class1 property value.
int b=alpha;
}
}
Then Visual Studio comes up with: an object reference is required....
I must be really stupid as I have seen many examples of this on the internet but I don't get it working, so I would be thankful if anyone helped me.
You need access to object of that other class - in other words 'reference' (in your example class1)
var c1 = new class1();
then you can access it's members
var alpha = c1.alpha;
Depending on your project you can instantiate it inside class2 or pass it as a parameter to class2 constructor.
What you did here probably would work in JAVA.
In order to use a non-static field (in fact, to use a non-static anything) you need to have an instance of the object from which you want to access a non-static member.
In this case, the nested class class2
needs to have a reference to its outer class. This could be passed in a constructor, or in a method call.
For example, here is one way of making it work:
public class class1
{
int a;
public int alpha{ get { return a; } }
public void Method1()
{
a++;
class2 c2 = new class2(this);
Console.WriteLine("{0}", c2.b);
}
public class class2
{
public int b;
public class2(class1 outer) {
b = outer.alpha;
}
}
}
在您的示例中,您需要实例化class1的实例以访问class2中的变量。
it should be like this
public class class1
{
int a;
public int alpha{ get { return a; } }
public void Method1()//method gets called...
{
a++;
}
}
public class class2
{
// Here initializing class2 variable as class1 property value.
class1 obj = new class1();
int b= obj.alpha;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.