我继承了一些代码,它们是一些常规类,其中包含一些私有静态方法。代码(伪代码)看起来像这样什么时候在实例类中使用私有静态方法是有意义的
public class Animal
{
private string typeOfAnimal;
public Animal(string typeOfAnimal)
{
this.typeOfAnimal = typeOfAnimal;
}
public void MakeSound()
{
var sound = Animal.GetSound(typeOfAnimal);
// Make use of sound here
}
private static string GetSound(string typeOfAnimal)
{
if(typeOfAnimal == "dog")
return "bark";
else if(typeOfAnimal == "cat")
return "mjau";
}
}
与使GetSound成为常规实例方法相比,这样做有什么好处吗?
一件事静态方法可以做到这一点的实例方法不能就是被称为供应参数传递给基类构造函数或转发构造函数。 – Kyle