Csharp/CSharp Tutorial/Class/Constructor

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Add a constructor to Triangle.

using System; 
 
class Shape { 
  double pri_width;  // private 
  double pri_height; // private  
 
  public double width { 
     get { return pri_width; } 
     set { pri_width = value; } 
  } 
 
  public double height { 
     get { return pri_height; } 
     set { pri_height = value; } 
  } 
 
  public void showDim() { 
    Console.WriteLine("Width and height are " + 
                       width + " and " + height); 
  } 
} 
 
class Triangle : Shape { 
  string style; // private 
   
  public Triangle(string s, double w, double h) { 
    width = w;  // init the base class 
    height = h; // init the base class 
 
    style = s;  // init the derived class 
  } 
 
  // Return area of triangle. 
  public double area() { 
    return width * height / 2;  
  } 
 
  // Display a triangle"s style. 
  public void showStyle() { 
    Console.WriteLine("Triangle is " + style); 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    Triangle t1 = new Triangle("isosceles", 4.0, 4.0); 
    Triangle t2 = new Triangle("right", 8.0, 12.0); 
 
    Console.WriteLine("Info for t1: "); 
    t1.showStyle(); 
    t1.showDim(); 
    Console.WriteLine("Area is " + t1.area()); 
 
    Console.WriteLine(); 
 
    Console.WriteLine("Info for t2: "); 
    t2.showStyle(); 
    t2.showDim(); 
    Console.WriteLine("Area is " + t2.area()); 
  } 
}
Info for t1:
Triangle is isosceles
Width and height are 4 and 4
Area is 8
Info for t2:
Triangle is right
Width and height are 8 and 12
Area is 48

Add a constructor with three parameters

using System;  
  
class Building {   
  public int floors;    
  public int area;      
  public int occupants; 
 
 
  public Building(int f, int a, int o) { 
    floors = f; 
    area = a; 
    occupants = o; 
  } 
 
  public int areaPerPerson() {  
    return area / occupants; 
  }  
 
  public int maxOccupant(int minArea) { 
    return area / minArea; 
  } 
}   
   
class MainClass {   
  public static void Main() {   
    Building house = new Building(2, 2500, 4);   
    Building office = new Building(3, 4200, 25); 
 
    Console.WriteLine("Maximum occupants for house if each has " + 
                      300 + " square feet: " + 
                      house.maxOccupant(300)); 
 
    Console.WriteLine("Maximum occupants for office if each has " + 
                      300 + " square feet: " + 
                      office.maxOccupant(300)); 
  }   
}
Maximum occupants for house if each has 300 square feet: 8
Maximum occupants for office if each has 300 square feet: 14

Add constructor to class

  1. A constructor initializes an object when it is created.
  2. A constructor has the same name as its class
  3. A constructor is syntactically similar to a method.
  4. Constructors have no explicit return type.

The general form of constructor is shown here:


access class-name( ) {
// constructor code
}

An overloaded constructor.

using System; 
 
class MyClass {  
  public int x;  
  
  public MyClass() { 
    Console.WriteLine("Inside MyClass()."); 
    x = 0; 
  } 
 
  public MyClass(int i) {  
    Console.WriteLine("Inside MyClass(int)."); 
    x = i;  
  } 
 
  public MyClass(double d) { 
    Console.WriteLine("Inside MyClass(double)."); 
    x = (int) d; 
  } 
 
  public MyClass(int i, int j) { 
    Console.WriteLine("Inside MyClass(int, int)."); 
    x = i * j; 
  }    
}    
    
class MainClass {    
  public static void Main() {    
    MyClass t1 = new MyClass();  
    MyClass t2 = new MyClass(88);  
    MyClass t3 = new MyClass(17.23);  
    MyClass t4 = new MyClass(2, 4);  
  
    Console.WriteLine("t1.x: " + t1.x); 
    Console.WriteLine("t2.x: " + t2.x); 
    Console.WriteLine("t3.x: " + t3.x); 
    Console.WriteLine("t4.x: " + t4.x); 
  } 
}
Inside MyClass().
Inside MyClass(int).
Inside MyClass(double).
Inside MyClass(int, int).
t1.x: 0
t2.x: 88
t3.x: 17
t4.x: 8

A parameterized constructor

using System; 
 
class MyClass { 
  public int x; 
 
  public MyClass(int i) { 
    x = i; 
  }   
}   
   
class MainClass {   
  public static void Main() {   
    MyClass t1 = new MyClass(10); 
    MyClass t2 = new MyClass(88); 
 
    Console.WriteLine(t1.x + " " + t2.x); 
  }   
}
10 88

Class without default constructor

public class MyClass
{
   public MyClass( int x, int y )
   {
      this.x = x;
      this.y = y;
   }
   public int x;
   public int y;
}
public class EntryPoint
{
   static void Main()
   {
      // We can"t do this!
      // MyClass objA = new MyClass();
      MyClass objA = new MyClass( 1, 2 );
      System.Console.WriteLine( "objA.x = {0}, objA.y = {1}",
                                objA.x, objA.y );
   }
}
objA.x = 1, objA.y = 2

Constuctor hidden

using System;
public class Class1 {
    public static void Main(string[] args) {
        SubClass sc1 = new SubClass();
        SubClass sc2 = new SubClass(0);
    }
}
public class BaseClass {
    public BaseClass() {
        Console.WriteLine("Constructing BaseClass (default)");
    }
    public BaseClass(int i) {
        Console.WriteLine("Constructing BaseClass (int)");
    }
}
public class SubClass : BaseClass {
    public SubClass() {
        Console.WriteLine("Constructing SubClass (default)");
    }
    public SubClass(int i) {
        Console.WriteLine("Constructing SubClass (int)");
    }
}

Copy constructor

using System;  
  
class Stack {   
  char[] stck; // holds the stack  
  int tos;     // index of the top of the stack  
   
  public Stack(int size) {   
    stck = new char[size];
    tos = 0;   
  }   
  
  public Stack(Stack ob) {   
    stck = new char[ob.stck.Length]; 
 
    for(int i=0; i < ob.tos; i++)  
      stck[i] = ob.stck[i]; 
 
    tos = ob.tos; 
  }   
  
  public void push(char ch) {   
    if(tos==stck.Length) {   
      Console.WriteLine(" -- Stack is full.");   
      return;   
    }   
       
    stck[tos] = ch;  
    tos++;  
  }   
   
  public char pop() {   
    if(tos==0) {   
      Console.WriteLine(" -- Stack is empty.");   
      return (char) 0;    
    }   
     
    tos--;   
    return stck[tos];   
  } 
 
  public bool full() { 
    return tos==stck.Length;    
  } 
 
  public bool empty() { 
    return tos==0; 
  } 
 
  public int capacity() { 
    return stck.Length; 
  } 
 
  public int getNum() { 
    return tos; 
  } 
} 
 
class MainClass {   
  public static void Main() {   
    Stack stk1 = new Stack(10);   
    char ch;   
    int i;   
   
    Console.WriteLine("Push A through J onto stk1."); 
    for(i=0; !stk1.full(); i++)   
      stk1.push((char) ("A" + i));   
 
    Stack stk2 = new Stack(stk1); 
  
    Console.Write("Contents of stk1: ");   
    while( !stk1.empty() ) {    
      ch = stk1.pop();   
      Console.Write(ch);   
    }   
 
    Console.WriteLine(); 
   
    Console.Write("Contents of stk2: ");   
    while ( !stk2.empty() ) {    
      ch = stk2.pop();   
      Console.Write(ch);   
    }   
 
    Console.WriteLine("\n"); 
    
  }   
}
Push A through J onto stk1.
Contents of stk1: JIHGFEDCBA
Contents of stk2: JIHGFEDCBA

Invoke a constructor through this

The general form is shown here:


constructor-name(parameter-list1) : this(parameter-list2) {
// ... body of constructor, which may be empty
}

Multiple Constructor version without duplicating a lot of the constructor code

using System;
public class BankAccount {
    static int nNextAccountNumber = 1000;
    int nAccountNumber;
    double dBalance;
    public BankAccount() : this(0, 0) { }
    public BankAccount(double dInitialBalance) :
        this(0, dInitialBalance) { }
    public BankAccount(int nInitialAccountNumber,
                       double dInitialBalance) {
        if (nInitialAccountNumber <= 0) {
            nInitialAccountNumber = ++nNextAccountNumber;
        }
        nAccountNumber = nInitialAccountNumber;
        if (dInitialBalance < 0) {
            dInitialBalance = 0;
        }
        dBalance = dInitialBalance;
    }
    public string GetString() {
        return String.Format("#{0} = {1:N}",
                              nAccountNumber, dBalance);
    }
}

Private copy constructor used when making a copy of this object

using System;
public sealed class Dimensions : ICloneable
{
    public Dimensions( long width, long height ) {
        this.width = width;
        this.height = height;
    }
    private Dimensions( Dimensions other ) {
        this.width = other.width;
        this.height = other.height;
    }
    public object Clone() {
        return new Dimensions(this);
    }
    
    private long width;
    private long height;
}

Use Constructor to initialize member variables

using System;
class MyClass
{
  public int[] MyIntArray;
  public int Y;
  public int ObjectCount = 0;
  
  public MyClass()
  {
    MyIntArray = new int[10];
    //Do work necessary during object creation
  }
  //Overloads the MyClass allowing you to initialize Y
  public MyClass(int myY)
  {
    Y = myY;
  }
}
class MainClass{
  static void Main(string[] args)
  {
    MyClass X = new MyClass();
    X.ObjectCount++;
    MyClass YY = new MyClass(10);
  }
}