代码之家  ›  专栏  ›  技术社区  ›  James

C#-从类内部调用方法

  •  1
  • James  · 技术社区  · 17 年前

    如何从客户端代码中定义的类内部调用客户端代码方法?

    例如,我有一个内存读取类,它可以从某个地址的进程内存中读取值。我还有用于管理从内存中读取的数据类型的类(我正在阅读一个游戏中的“对象”。在“客户端代码”中,我正在计算内存中该对象的“基址”,然后使用一个将“基址“作为参数的构造函数初始化我的“对象类”。然后,这个基类应该能够通过方法告诉我关于该对象的事情,因为对象知道某个值离基址有多远,比如“健康”)

    我尝试使用这样的代码,但它给了我一个错误。“ObjectManager”是可以从内存中读取值的类。

    class ObjectManager : Memory
    {
        LocalCharacter LocalPlayer = new LocalCharacter(this);
        // other things omitted
    }
    // Error: Keyword 'this' is not available in the current context
    

    这是出于绝望:

    class ObjectManager : Memory
    {
        LocalCharacter LocalPlayer = new LocalCharacter(ObjectManager);
        // other things omitted
    }
    // Error: Keyword 'this' is not available in the current context
    

    但无济于事。最好的方法是什么?

    2 回复  |  直到 17 年前
        1
  •  10
  •   ljs TheVillageIdiot    17 年前

    在构造函数中引用“this”怎么样:-

    class ObjectManager : Memory
    {
        ObjectManager()
        {
            LocalPlayer = new LocalCharacter(this);
        }
    
        LocalCharacter LocalPlayer;
        // other things omitted
    }
    
        2
  •  0
  •   Spence    17 年前

    因为你没有方法。

    您必须声明一个方法来访问它。您的main函数将调用该调用。

    如果你想设置一个类级字段,那么你需要在构造函数中这样做。不过,您仍然在类定义中声明变量(而不是在方法中)

    class ObjectManager : Memory
    {
       public void mymethod()
       {
          LocalCharacter LocalPlayer = new LocalCharacter(this);
       }
    }
    
    推荐文章