每次要使用类中的函数时调用'new'

  • 本文关键字:函数 调用 new c# class
  • 更新时间 :
  • 英文 :


可以写这样的类吗:

public class AlexaApi
{
public string CreateRandomPhrase()
{
return "Hello World" //There's more code, but needless for my question
}
public object ResponseBuilder(string text)
{
//CODE HERE
}
}

但是,当我使用这个类时,每次我想访问它的函数时,都要调用"new"。

new AlexaApi().ResponseBuilder(new AlexaApi().CreateRandomPhrase());

我知道这创建了AlexaApi对象的两个实例,它很可能应该写成:

var alexa = new AlexaApi();
alexa.ResponseBuilder(alexa.CreateRandomPhrase());

每次调用"new"都会占用更多内存吗?可能发生的最糟糕的事情是什么?按照第一个例子写的做真的不好吗?

您实际想要的很有可能是static方法:

public class AlexaApi
{
public static string CreateRandomPhrase()
{
return "Hello World" //There's more code, but needless for my question
}
public static object ResponseBuilder(string text)
{
//CODE HERE
}
}

然后可以这样调用这些方法:

AlexaApi.CreateRandomPhrase();
..etc.

也就是说,你避免每次都建立一个新的类。

但是要注意,static方法和类与static方法和类具有略微不同的对称性。特别是

  • 不能在类中存储状态
  • 内存中只有一个方法实例(这可能会提高内存效率,但如果不小心,也可能导致内存泄漏(
  • 静态对象可能是单元测试中的一个问题,因为它们不能注入

您没有显示这个类所做操作的详细信息,因此很难明确。如果你的方法只是"逻辑",那么使它们静态也没有害处。如果他们加载资源等,那么就不要加载。

有关更多信息,请参阅静态与非静态类成员

还要注意,一个只包含static方法的类本身可以被设为static。这只是防止您声明无静态方法/属性

public static class AlexaApi
{
public static string CreateRandomPhrase()
{
return "Hello World" //There's more code, but needless for my question
}
public static object ResponseBuilder(string text)
{
//CODE HERE
}
}

要在不创建多个实例的情况下完成所有这些操作,您应该按照建议静态方法。考虑以下代码:

public class AlexaApi
{
public static string CreateRandomPhrase()
{
return "Hello World" //There's more code, but needless for my question
}
public static object ResponseBuilder(string text)
{
//CODE HERE
}
}

通过这种方式,您可以使用以下代码获得相同的结果:

AlexaApi.ResponseBuilder(AlexaApi.CreateRandomPhrase());

关键字static应该适合您的情况:

public class AlexaApi
{
public static string CreateRandomPhrase()
{
return "Hello World" //There's more code, but needless for my question
}
public static object ResponseBuilder(string text)
{
//CODE HERE
}
}

并在不创建实例的情况下直接调用方法:

AlexaApi.ResponseBuilder(AlexaApi.CreateRandomPhrase());

正如您在问题中提到的,每次使用类的新实例都会占用更多内存。根据调用此方法的范围和类的大小(有多少实例变量,而不是代码行(,这实际上可能几乎没有额外的内存(ram存储类的额外实例(或CPU时间(使用任何默认值/构造函数创建类(,消耗的内存比程序其他部分加起来还要多。

正如我在打字时发布的评论和答案中所提到的,您可以始终将这些方法设置为static,这意味着可以在根本不使用类实例的情况下调用它们,这将为您省去麻烦。

最新更新