Csharp/CSharp Tutorial/Class/private
Содержание
Define private constructors to make a singleton
<source lang="csharp">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); } }
}</source>
private static and const Fields
<source lang="csharp">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; }</source>
Use Properties to get and set private member variable
<source lang="csharp">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; }
}</source>
Using Methods to change private fields
<source lang="csharp">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; } }</source>