简体   繁体   English

另一个类中的非静态变量

[英]non-static variable in another class

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.... 然后Visual Studio提出:需要一个对象引用....

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) 您需要访问该其他类的对象 - 换句话说'引用'(在您的示例中为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. 根据您的项目,您可以在class2中实例化它或将其作为参数传递给class2构造函数。

What you did here probably would work in JAVA. 你在这里做的可能适用于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. 在这种情况下,嵌套类class2需要引用其外部类。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM