在 .NET MVC 应用程序中从静态方法更改为非静态方法

Change from static to non static method in .NET MVC app

我的 MVC 应用程序中有一个方法可以创建一个 pdf 文件(将一个对象与要写入的数据和路径作为参数)。我在单独的 class 中编写了该方法,并将其设为静态。在我的控制器的另一个函数中,我这样调用这个方法:

PdfGenerator.GeneratePdfMethod("write this string", "path");

现在,如果我将此方法更改为非静态方法,我必须实例化一个 PdfGenerator 对象,然后调用该对象上的函数:

PdfGenerator p = new PdfGenerator();
p.GeneratePdfMethod("write this string", "path");

现在我怎样才能避免在不使我的方法静态化的情况下必须创建这个对象?如果它甚至是可能的和可取的?

Now how can i avoid having to create this object while not making my method static? If it is even possible ...?

没有。您必须先创建 class 的实例,然后才能访问其任何成员,包括 GeneratePdfMethod 方法。

不过您可以在一行中完成此操作:

new PdfGenerator().GeneratePdfMethod("write this string", "path");

当成员是 static 时,它不属于特定实例,而是属于类型本身。

相反,非静态方法属于特定实例,这意味着您需要在调用该方法之前引用该特定实例。

如果GeneratePdfMethod不访问任何实例数据,它应该是static