简体   繁体   English

来自另一个类的 C# 访问变量,没有静态

[英]C# access variable from another class without static

I'm trying to access some variables from different classes in one of my classes, I would like to be able to get the value and set the value of those variable from other classes.我正在尝试从我的一个类中的不同类访问一些变量,我希望能够从其他类中获取值并设置这些变量的值。

Right now, I'm using static but I'm using it too much and I think that's not good practice.现在,我正在使用静态,但我使用它太多了,我认为这不是一个好习惯。

So I'm trying to do with getters and setters but I can't make it work.所以我正在尝试使用 getter 和 setter,但我无法让它发挥作用。 Here is a small example of what I'm doing right now :这是我现在正在做的一个小例子:

generalManager file总经理档案

public float eggs ; 

public float getEggs(){
    return eggs ; 
}

gameManager file游戏管理器文件

generalManager.getEggs() ;

And I have this error :我有这个错误:

Assets/Scripts/gameManager.cs : error CS0120: An object reference is required for the non-static field, method, or property 'generalManager.eggs')

And I have to admit that I don't know what can I do to do not have this error anymore.而且我不得不承认,我不知道该怎么做才能不再出现此错误。

You can access the variables of a class only in two ways:您只能通过两种方式访问​​类的变量:

  1. Make the variable static.使变量静态。
public class GeneralManager
{
    public static float Eggs;
}

and use the variable in the GameManager like GeneralManager.Eggs并使用GameManager中的变量,如GeneralManager.Eggs

  1. Create an object of that class in the second class.在第二个类中创建该类的对象。 For example, the GeneralManager class will look like this例如,GeneralManager 类将如下所示
public class GeneralManager
{
    public string Eggs
}

and inside the GameManager, do this在 GameManager 中,执行此操作

GeneralManager generalManager = new GeneralManager()
float eggsLeft = generalManager.Eggs

Note: In the second case, if you create multiple objects of the GeneralManager class, the value of eggs will be different in every instance.注意:第二种情况,如果你创建了多个GeneralManager类的对象,那么eggs的值在每个实例中都是不同的。 For example, if two of your classes have the generalManger object created and you update the value of Eggs from one class, the object in the other class will remain unchanged.例如,如果您的两个类创建了 generalManger 对象,并且您从一个类更新 Eggs 的值,则另一个类中的对象将保持不变。 In that case, use the 1st method.在这种情况下,请使用第一种方法。

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

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