Csharp/C Sharp/Class Interface/Static — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 11:38, 26 мая 2010
Содержание
- 1 Can call a non-static method through an object reference from within a static method
- 2 Demonstrates access to static and non-static members
- 3 Demonstrates how a static field is shared by multiple instances of a class
- 4 Demonstrates use of static constructor
- 5 Error using static
- 6 Illustrates the use of static members
- 7 Static members are frequently used as counters.
- 8 Use a static class factory
- 9 Use a static constructor
- 10 Use a static field to count instances
- 11 Use static
- 12 Use static method to initialize field
Can call a non-static method through an object reference from within a static method
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System;
public class MyClass {
// non-static method.
void nonStaticMeth() {
Console.WriteLine("Inside nonStaticMeth().");
}
/* Can call a non-static method through an
object reference from within a static method. */
public static void staticMeth(MyClass ob) {
ob.nonStaticMeth(); // this is OK
}
}
Demonstrates access to static and non-static members
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// Members.cs -- Demonstrates access to static and non-static members
//
// Compile this program using the following command line:
// C:>csc Members.cs
//
namespace nsMembers
{
using System;
public class StaticMembers
{
static public void Main ()
{
// Access a static member using the class name.
// You may access a static
// member without creating an instance of the class
Console.WriteLine ("The static member is pi: " + clsClass.pi);
// To access a non-static member, you must create an instance
// of the class
clsClass instance = new clsClass();
// Access a static member using the name of the variable
// containing the
// instance reference
Console.WriteLine ("The instance member is e: " + instance.e);
}
}
class clsClass
{
// Declare a static field. You also could use the const
// keyword instead of static
static public double pi = 3.14159;
// Declare a normal member, which will be created when you
// declare an instance
// of the class
public double e = 2.71828;
}
}
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// Static.cs -- Demonstrates how a static field is shared by
// multiple instances of a class.
//
// Compile this program with the following command line:
// C:>csc Static.cs
//
namespace nsStatic
{
using System;
public class clsMainStatic
{
static public void Main ()
{
for (int i = 0; i < 20; ++i)
{
clsStatic inst = new clsStatic();
}
Console.WriteLine ("Created {0} instance of clsStatic",
clsStatic.Count);
}
}
class clsStatic
{
static public int Count
{
get {return (m_Count);}
}
static private int m_Count = 0;
public clsStatic ()
{
++m_Count;
}
}
}
Demonstrates use of static constructor
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// SysInfo.cs -- Demonstrates use of static constructor
//
// Compile this program with the following command line:
// C:>csc SysInfo.cs
//
namespace nsSysInfo
{
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class SysInfo
{
static public void Main()
{
Console.WriteLine ("Current user is " +
clsSystemInfo.User);
Console.WriteLine ("Current Time Zone is " +
clsSystemInfo.TZ);
Console.WriteLine ("Current domain is " +
clsSystemInfo.Domain);
Console.WriteLine ("Current Host is " +
clsSystemInfo.Host);
Console.WriteLine ("Command interpreter is " +
clsSystemInfo.ruSpec);
}
}
class clsSystemInfo
{
private clsSystemInfo () {}
[DllImport ("kernel32.dll")]
static extern public long GetEnvironmentVariable (string name,
byte [] value, long size);
static clsSystemInfo ()
{
m_User = SystemInformation.UserName;
m_Host = SystemInformation.ruputerName;
DateTime now = DateTime.Now;
TimeZone tz = TimeZone.CurrentTimeZone;
m_TimeZone = tz.IsDaylightSavingTime(now)
? tz.DaylightName : tz.StandardName;
m_Domain = SystemInformation.UserDomainName;
byte [] comspec = new byte [256];
if (GetEnvironmentVariable ("COMSPEC", comspec, 256) > 0)
{
foreach (byte ch in comspec)
{
if (ch == 0)
break;
m_ComSpec += (char) ch;
}
}
}
static public string User
{
get
{
return (m_User);
}
}
static public string TZ
{
get
{
return (m_TimeZone);
}
}
static public string Domain
{
get
{
return (m_Domain);
}
}
static public string Host
{
get
{
return (m_Host);
}
}
static public string ComSpec
{
get
{
return (m_ComSpec);
}
}
private static string m_User;
private static string m_TimeZone;
private static string m_Domain;
private static string m_Host;
private static string m_ComSpec;
}
}
Error using static
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System;
public class AnotherStaticError {
// non-static method.
void nonStaticMeth() {
Console.WriteLine("Inside nonStaticMeth().");
}
/* Error! Can"t directly call a non-static method
from within a static method. */
static void staticMeth() {
nonStaticMeth(); // won"t compile
}
}
Illustrates the use of static members
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example6_1.cs illustrates the use of static members
*/
// declare the Car class
class Car
{
// declare a static field,
// numberOfCars stores the number of Car objects
private static int numberOfCars = 0;
// define the constructor
public Car()
{
System.Console.WriteLine("Creating a Car object");
numberOfCars++; // increment numberOfCars
}
// define the destructor
~Car()
{
System.Console.WriteLine("Destroying a Car object");
numberOfCars--; // decrement numberOfCars
}
// define a static method that returns numberOfCars
public static int GetNumberOfCars()
{
return numberOfCars;
}
}
public class Example6_1
{
public static void Main()
{
// display numberOfCars
System.Console.WriteLine("Car.GetNumberOfCars() = " +
Car.GetNumberOfCars());
// create a Car object
Car myCar = new Car();
System.Console.WriteLine("Car.GetNumberOfCars() = " +
Car.GetNumberOfCars());
// create another Car object
Car myCar2 = new Car();
System.Console.WriteLine("Car.GetNumberOfCars() = " +
Car.GetNumberOfCars());
}
}
Static members are frequently used as counters.
using System;
public class Starter {
public static void Main() {
MyClass<int> obj1 = new MyClass<int>();
MyClass<double> obj2 = new MyClass<double>();
MyClass<double> obj3 = new MyClass<double>();
MyClass<int>.Count(obj1);
MyClass<double>.Count(obj2);
}
}
public class MyClass<T> {
public MyClass() {
++counter;
}
public static void Count(MyClass<T> _this) {
Console.WriteLine("{0} : {1}",
_this.GetType().ToString(),
counter.ToString());
}
private static int counter = 0;
}
Use a static class factory
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use a static class factory.
using System;
class MyClass {
int a, b;
// Create a class factory for MyClass.
static public MyClass factory(int i, int j) {
MyClass t = new MyClass();
t.a = i;
t.b = j;
return t; // return an object
}
public void show() {
Console.WriteLine("a and b: " + a + " " + b);
}
}
public class MakeObjects1 {
public static void Main() {
int i, j;
// generate objects using the factory
for(i=0, j=10; i < 10; i++, j--) {
MyClass ob = MyClass.factory(i, j); // get an object
ob.show();
}
Console.WriteLine();
}
}
Use a static constructor
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use a static constructor.
using System;
class Cons {
public static int alpha;
public int beta;
// static constructor
static Cons() {
alpha = 99;
Console.WriteLine("Inside static constructor.");
}
// instance constructor
public Cons() {
beta = 100;
Console.WriteLine("Inside instance constructor.");
}
}
public class ConsDemo {
public static void Main() {
Cons ob = new Cons();
Console.WriteLine("Cons.alpha: " + Cons.alpha);
Console.WriteLine("ob.beta: " + ob.beta);
}
}
Use a static field to count instances
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use a static field to count instances.
using System;
class CountInst {
static int count = 0;
// increment count when object is created
public CountInst() {
count++;
}
// decrement count when object is destroyed
~CountInst() {
count--;
}
public static int getcount() {
return count;
}
}
public class CountDemo {
public static void Main() {
CountInst ob;
for(int i=0; i < 10; i++) {
ob = new CountInst();
Console.WriteLine("Current count: " +
CountInst.getcount());
}
}
}
Use static
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use static.
using System;
class StaticDemo {
// a static variable
public static int val = 100;
// a static method
public static int valDiv2() {
return val/2;
}
}
public class SDemo {
public static void Main() {
Console.WriteLine("Initial value of StaticDemo.val is "
+ StaticDemo.val);
StaticDemo.val = 8;
Console.WriteLine("StaticDemo.val is " + StaticDemo.val);
Console.WriteLine("StaticDemo.valDiv2(): " +
StaticDemo.valDiv2());
}
}
Use static method to initialize field
using System;
internal class MyClass {
public int iField1 = FuncA();
public int iField2 = FuncC();
public int iField3 = FuncB();
public static int FuncA() {
Console.WriteLine("MyClass.FuncA");
return 0;
}
public static int FuncB() {
Console.WriteLine("MyClass.FuncB");
return 1;
}
public static int FuncC() {
Console.WriteLine("MyClass.FuncC");
return 2;
}
}
public class Starter {
public static void Main() {
MyClass obj = new MyClass();
}
}