如何从C#中的另一个类调用变量

时间:2013-01-13 11:18:28

标签: c# oop

我来自Java,我正在接受C#脚本编写,我已经有两天这个问题了,现在正在寻找解决方案,我已经尝试将类设置为实例和所有内容。这是一个微型游戏项目,我正和一些朋友一起工作。

无论哪种方式,我都有StatHandler.cs来处理我们所有的状态点...然后我有HealthManager.cs,它应该处理所有与Health相关的东西。

问题是,我不能为我的生活弄清楚如何调用诸如

之类的变量
public int stamina, strength, agility, dexterity, wisdom;

来自StatHandler.cs

我知道在Java中它会像

一样简单
maxHealth = StatHandler.stamina * 10;

虽然你不能用C#做到这一点,但在创建实例时,代码看起来像这样

maxHealth = StatHandler.instance.stamina * 10;

它为我提供了错误

NullReferenceException: Object reference not set to an instance of an object

我也尝试过继承,通过这样做

public class HealthHandler : StatHandler {

但它在HealthHandler类中将所有值设置为0,它不会读取任何内容。


我真的只需要弄清楚如何从其他C#文件中提取变量,因为这会减慢我的速度。

4 个答案:

答案 0 :(得分:3)

它实际上与Java相同。对于非静态变量,您需要一个类实例:

StatHandler sh = new StatHandler();
maxHealth = sh.stamina * 10;

或者您可以在类中将变量声明为静态,如

public static string stamina = 10;

然后访问它

maxHealth = StatHandler.stamina * 10;

答案 1 :(得分:0)

在C#中,如果不初始化它,就不能使用值类型变量。

看起来StatHandler.instancestatic方法。未经分配,您无法使用int变量。为它们分配一些值。

例如

public int stamina = 1, strength = 2, agility = 3, dexterity = 4, wisdom = 5;

答案 2 :(得分:0)

  

NullReferenceException:未将对象引用设置为对象的实例

您需要正确初始化。似乎StatHandler.instance是静态的而未初始化。

您可以在static构造函数

中初始化它
class StatHandler
{

  static StatHandler()
  {
      instance = new Instance(); // Replace Instance with type of instance
  }
}

答案 3 :(得分:0)

你有两种方法可以去这里。

完整静态类

public static class StatHandler
{
    public static Int32 Stamina = 10;
    public static Int32 Strength = 5;
}

然后:

maxHealth = StatHandler.Stamina * 10; // get the value and use it
StatHandler.Stamina = 19; // change the value

单身实例

public class StatHandler
{
    public static StatHandler Instance;

    public Int32 Stamina = 10;
    public Int32 Strength = 5;

    // this is called only the first time you invoke the class
    static StatHandler()
    {
        m_Instance = new Instance(); // Replace Instance with type of instance
    }
}

然后:

maxHealth = StatHandler.Instance.Stamina * 10; // get the value and use it
StatHandler.Instance.Stamina = 19; // change the value

// replace the current instance:
StatHandler.Instance = new StatHandler();
StatHandler.Instance.Stamina = 19; // change the value

我认为第一个总是最好的选择,同样的结果,更少的复杂性。

相关问题