从另一个类调用方法

N0x*_*xus 5 c#

我想知道如何从另一个类调用方法而不必创建该类的新实例。我查过这个,我看到的 90% 的例子都要求我制作我引用的类的新副本。

像这样的东西:

Fooclass test = new Fooclass();
test.CallMethod();
Run Code Online (Sandbox Code Playgroud)

但是,我想知道是否有一种方法可以在不创建新类实例的情况下调用该方法。现在我已经统一尝试了以下内容。

public ImageLoader image; 
void Start () 
{
    image = gameObject.GetComponent<ImageLoader>() as ImageLoader;
}

void OnClick()
{
    image.MoveForward();
}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行它时,我收到以下错误:

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

我知道这将通过创建我的图像加载器类的新实例来解决,但我不能这样做,因为它保存了很多我不想多次重复的数据。

Chr*_*tos 5

是的你可以。第一种方法是让你的类是静态的。

public static class Fooclass
{
    // I don't know the return type of your CallMethod, so I used the void one.
    public static void CallMethod()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

这样,无论何时,您都可以调用您的代码CallMethod(),如下所示:

Fooclass.CallMethod()
Run Code Online (Sandbox Code Playgroud)

另一种方法是在当前类中定义一个静态方法,而该类不需要是静态的,如下所示:

public class Fooclass
{
    // I don't know the return type of your CallMethod, so I used the void one.
    public static void CallMethod()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

现在,由于 的所有实例都Fooclass将共享相同的方法CallMethod,您可以像下面这样调用它:

Fooclass.CallMethod()
Run Code Online (Sandbox Code Playgroud)

无需再次实例化 Fooclass 类型的对象,尽管现在 Fooclass 不是静态类!

有关更多文档,请查看链接静态类和静态成员