currInterestRate = 0.04;
currBalance = balance;
}
...
}
If you execute the previous Main() method, notice how the currInterestRate variable is reset
each time you create a new SavingsAccount object (see Figure 5-7).
Figure 5-7.
Assigning static data in an instance level constructor “resets” the value.
While you are always free to establish the initial value of static data using the member initial-
ization syntax, what if the value for your static data needed to be obtained from a database or
external file? To perform such tasks requires a method scope (such as a constructor) to execute the
code statements. For this very reason, C# allows you to define a static constructor:
class SavingsAccount
{
public double currBalance;
public static double currInterestRate;
public SavingsAccount(double balance)
{
currBalance = balance;
}
Do'stlaringiz bilan baham: |