Материал из .Net Framework эксперт
Define private constructors to make a singleton
public class MyClass
{
static MyClass cache = null;
static object cacheLock = new object();
private MyClass()
{
// useful stuff here
}
public static MyClass GetMyClass()
{
lock(cacheLock)
{
if (cache == null)
cache = new MyClass();
return(cache);
}
}
}
private static and const Fields
using System;
class MainClass
{
static void Main(string[] args)
{
MyTV tv = new MyTV();
}
}
public class MyTV
{
public MyTV()
{
channel = 2;
}
private static int channel = 2;
private const int maxChannels = 200;
}
Use Properties to get and set private member variable
using System;
class Circle{
int radius;
public int Radius{
get{
return(radius);
}
set{
radius = value;
}
}
}
class MainClass
{
public static void Main()
{
Circle c = new Circle();
c.Radius = 35;
}
}
Using Methods to change private fields
using System;
class Class1
{
static void Main(string[] args)
{
MyCar car = new MyCar();
int refChan = 0;
int chan = 0;
car.GetSpeed( chan );
car.GetSpeed( ref refChan );
}
}
public class MyCar
{
private static int speed = 2;
private const int maxSpeed = 200;
public bool ChangeSpeed(int newSpeed)
{
if( newSpeed > maxSpeed )
return false;
speed = newSpeed;
return true;
}
public void GetSpeed( int param )
{
param = speed;
}
public void GetSpeed( ref int param )
{
param = speed;
}
}