Defining Static Methods (and Fields)
Assume you have a new Console Application project named StaticMethods and have inserted a
class named Teenager that defines a static method named Complain(). This method returns a ran-
dom string, obtained in part by calling a static helper function named GetRandomNumber():
class Teenager
{
public static Random r = new Random();
public static int GetRandomNumber(short upperLimit)
{
return r.Next(upperLimit);
}
public static string Complain()
{
string[] messages = {"Do I have to?", "He started it!",
"I'm too tired...", "I hate school!",
"You are sooooooo wrong!"};
return messages[GetRandomNumber(5)];
}
}
Notice that the System.Random member variable and the GetRandomNumber() helper function
method have also been declared as static members of the Teenager class, given the rule that static
members can operate only on other static members.
Do'stlaringiz bilan baham: |