【问题标题】:C# - Calling methods from inside classC# - 从类内部调用方法
【发布时间】:2009-01-27 09:45:21
【问题描述】:

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

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

我尝试使用这样的代码,但它给了我一个错误。 '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

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

【问题讨论】:

    标签: c# c#-3.0 reference methods


    【解决方案1】:

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

    class ObjectManager : Memory
    {
        ObjectManager()
        {
            LocalPlayer = new LocalCharacter(this);
        }
    
        LocalCharacter LocalPlayer;
        // other things omitted
    }
    

    【讨论】:

      【解决方案2】:

      因为你不在一个方法中。

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

      如果您希望设置类级别字段,则需要在构造函数中进行。您仍然在类定义中声明变量(而不是在方法中)

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-28
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多