Csharp/C Sharp/Class Interface/Constructor — различия между версиями

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

Версия 15:31, 26 мая 2010

Add a constructor to Building

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Add a constructor to Building. 
  
using System;  
  
class Building {   
  public int floors;    // number of floors 
  public int area;      // total square footage of building 
  public int occupants; // number of occupants 
 
 
  public Building(int f, int a, int o) { 
    floors = f; 
    area = a; 
    occupants = o; 
  } 
 
  // Display the area per person.  
  public int areaPerPerson() {  
    return area / occupants; 
  }  
 
  /* Return the maximum number of occupants if each 
     is to have at least the specified minum area. */ 
  public int maxOccupant(int minArea) { 
    return area / minArea; 
  } 
}   
   
// Use the parameterized Building constructor. 
public class BuildingDemo21 {   
  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)); 
  }   
}


Add a constructor to Triangle

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Add a constructor to Triangle. 
 
using System; 
 
// A class for two-dimensional objects. 
class TwoDShape { 
  double pri_width;  // private 
  double pri_height; // private  
 
  // properties for width and height. 
  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); 
  } 
} 
 
// A derived class of TwoDShape for triangles. 
class Triangle : TwoDShape { 
  string style; // private 
   
  // Constructor 
  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); 
  } 
} 
 
public class Shapes3 { 
  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()); 
  } 
}


Add constructors to TwoDShape

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Add constructors to TwoDShape. 
 
using System; 
 
// A class for two-dimensional objects. 
class TwoDShape { 
  double pri_width;  // private 
  double pri_height; // private  
 
  // Constructor for TwoDShape. 
  public TwoDShape(double w, double h) { 
    width = w; 
    height = h; 
  } 
 
  // properties for width and height. 
  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); 
  } 
} 
 
 // A derived class of TwoDShape for triangles. 
class Triangle : TwoDShape { 
  string style; // private 
   
  // Call the base class constructor. 
  public Triangle(string s, double w, double h) : base(w, h) { 
    style = s;  
  } 
 
  // Return area of triangle. 
  public double area() { 
    return width * height / 2; 
  } 
 
  // Display a triangle"s style. 
  public void showStyle() { 
    Console.WriteLine("Triangle is " + style); 
  } 
} 
 
public class Shapes4 { 
  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()); 
  } 
}


Add more constructors to TwoDShape

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Add more constructors to TwoDShape. 
 
using System; 
 
class TwoDShape { 
  double pri_width;  // private 
  double pri_height; // private  
 
  // Default constructor. 
  public TwoDShape() { 
    width = height = 0.0; 
  } 
 
  // Constructor for TwoDShape. 
  public TwoDShape(double w, double h) { 
    width = w; 
    height = h; 
  } 
 
  // Construct object with equal width and height. 
  public TwoDShape(double x) { 
    width = height = x; 
  } 
 
  // Properties for width and height. 
  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); 
  } 
} 
 
// A derived class of TwoDShape for triangles. 
class Triangle : TwoDShape { 
  string style; // private 
   
  /* A default constructor. This automatically invokes 
     the default constructor of TwoDShape. */ 
  public Triangle() { 
    style = "null"; 
  } 
 
  // Constructor that takes three arguments. 
  public Triangle(string s, double w, double h) : base(w, h) { 
    style = s;  
  } 
 
  // Construct an isosceles triangle. 
  public Triangle(double x) : base(x) { 
    style = "isosceles";  
  } 
 
  // Return area of triangle. 
  public double area() { 
    return width * height / 2; 
  } 
 
  // Display a triangle"s style. 
  public void showStyle() { 
    Console.WriteLine("Triangle is " + style); 
  } 
} 
 
public class Shapes5 { 
  public static void Main() { 
    Triangle t1 = new Triangle(); 
    Triangle t2 = new Triangle("right", 8.0, 12.0); 
    Triangle t3 = new Triangle(4.0); 
 
    t1 = t2; 
 
    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()); 
 
    Console.WriteLine(); 
 
    Console.WriteLine("Info for t3: "); 
    t3.showStyle(); 
    t3.showDim(); 
    Console.WriteLine("Area is " + t3.area()); 
 
    Console.WriteLine(); 
  } 
}


A parameterized constructor

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// A parameterized constructor. 
 
using System; 
 
class MyClass { 
  public int x; 
 
  public MyClass(int i) { 
    x = i; 
  }   
}   
   
public class ParmConsDemo {   
  public static void Main() {   
    MyClass t1 = new MyClass(10); 
    MyClass t2 = new MyClass(88); 
 
    Console.WriteLine(t1.x + " " + t2.x); 
  }   
}


A simple constructor

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// A simple constructor. 
 
using System; 
 
class MyClass { 
  public int x; 
 
  public MyClass() { 
    x = 10; 
  }   
}   
   
public class ConsDemo1 {   
  public static void Main() {   
    MyClass t1 = new MyClass(); 
    MyClass t2 = new MyClass(); 
 
    Console.WriteLine(t1.x + " " + t2.x); 
  }   
}


C# Class Constructor Overloading

public Overloading
{
    public static void Main()
    {
        Point myPoint = new Point(10, 15);
        Point mySecondPoint = new Point(myPoint);
    }
}
class Point
{
    // create a new point from x and y values
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
    // create a point from an existing point
    public Point(Point p)
    {
        this.x = p.x;
        this.y = p.y;
    }
    
    int x;
    int y;
}


Check the parameter in construtor

 
using System;
public class Class1 {
    public static void Main(string[] args) {
        Student student = new Student("AAA", 1234);
        Console.WriteLine("Welcome new student {0}", student.GetString());
    }
}
public class Student {
    string sStudentName;
    int nStudentID;
    int nCreditHours;
    public Student(string sName, int nID) {
        if (sName == null) {
            sName = "invalid";
        }
        sStudentName = sName;
        if (nID < 0) {
            nID = 0;
        }
        nStudentID = nID;
        nCreditHours = 0;
    }
    public string GetString() {
        string s = String.Format("{0}({1})",sStudentName, nStudentID);
        return s;
    }
}


constructor initializers are called bottom-up but the constructors are invoked top-down starting with the constructor in the base class

 
using System;
public class Starter {
    public static void Main() {
        XClass obj = new XClass();
    }
}
public class MyClass {
    public MyClass(int param) {
        Console.WriteLine("MyClass constructor");
    }
}
public class YClass : MyClass {
    public YClass(int param) : base(YClass.MethodA()) {
        Console.WriteLine("YClass constructor");
    }
    public static int MethodA() {
        Console.WriteLine("YClass constructor initializer");
        return 0;
    }
}
public class XClass : YClass {
    public XClass() : base(XClass.MethodA()) {
        Console.WriteLine("XClass constructor");
    }
    public static new int MethodA() {
        Console.WriteLine("XClass constructor initializer");
        return 0;
    }
}


Constructor overloading 3

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 */
using System;
namespace Client.Chapter_5___Building_Your_Own_Classes
{
  public class CTORChapter
  {
    public int[] MyIntArray;
    public int Y;
    //Initialization can take place here
    private int ObjectCount = 0;
    static void Main(string[] args)
    {
      CTORChapter X = new CTORChapter();
      X.ObjectCount++;
      CTORChapter YY = new CTORChapter(10);
    }
    //Default CTORChapter
    CTORChapter()
    {
      MyIntArray = new int[10];
      //Do work necessary during object creation
    }
    //Overloads the CTOR allowing you to initialize Y
    CTORChapter(int myY)
    {
      Y = myY;
    }
  }
}


Demonstrate an overloaded constructor

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Demonstrate 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; 
  }    
}    
    
public class OverloadConsDemo {    
  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); 
  }    
}


Demonstrate invoking a constructor through this

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Demonstrate invoking a constructor through this. 
  
using System;  
  
class XYCoord {   
  public int x, y;   
   
  public XYCoord() : this(0, 0) { 
    Console.WriteLine("Inside XYCoord()"); 
  }  
 
  public XYCoord(XYCoord obj) : this(obj.x, obj.y) { 
    Console.WriteLine("Inside XYCoord(obj)"); 
  }  
 
  public XYCoord(int i, int j) {  
    Console.WriteLine("Inside XYCoord(int, int)"); 
    x = i; 
    y = j; 
  }     
}     
     
public class OverloadConsDemo1 {     
  public static void Main() {     
    XYCoord t1 = new XYCoord();   
    XYCoord t2 = new XYCoord(8, 9);   
    XYCoord t3 = new XYCoord(t2);   
   
    Console.WriteLine("t1.x, t1.y: " + t1.x + ", " + t1.y);  
    Console.WriteLine("t2.x, t2.y: " + t2.x + ", " + t2.y);  
    Console.WriteLine("t3.x, t3.y: " + t3.x + ", " + t3.y);  
  }     
}


Illustrates a copy constructor

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example5_13.cs illustrates a copy constructor
*/

// declare the Car class
class Car
{
  // declare the fields
  private string make;
  private string model;
  private string color;
  private int yearBuilt;
  // define the copy constructor
  public Car(Car car)
  {
    this.make = car.make;
    this.model = car.model;
    this.color = car.color;
    this.yearBuilt = car.yearBuilt;
  }
  public Car(string make, string model, string color, int yearBuilt)
  {
    this.make = make;
    this.model = model;
    this.color = color;
    this.yearBuilt = yearBuilt;
  }
  // define method to display the fields
  public void Display()
  {
    System.Console.WriteLine("make = " + make);
    System.Console.WriteLine("model = " + model);
    System.Console.WriteLine("color = " + color);
    System.Console.WriteLine("yearBuilt = " + yearBuilt);
  }
}

public class Example5_13
{
  public static void Main()
  {
    // create a Car object
    Car myCar = new Car("Toyota", "MR2", "black", 1995);
    // create a copy of this Car object
    Car carCopy = new Car(myCar);
    // display the values for the Car object"s fields
    System.Console.WriteLine("myCar details:");
    myCar.Display();
    System.Console.WriteLine("carCopy details:");
    carCopy.Display();
  }
}


Illustrates how to define a constructor

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example5_11.cs illustrates how to define a constructor
*/

// declare the Car class
class Car
{
  // declare the fields
  private string make;
  private string model;
  private string color;
  private int yearBuilt;
  // define the constructor
  public Car(string make, string model, string color, int yearBuilt)
  {
    System.Console.WriteLine("In Car() constructor");
    this.make = make;
    this.model = model;
    this.color = color;
    this.yearBuilt = yearBuilt;
  }
  // define a method to display the fields
  public void Display()
  {
    System.Console.WriteLine("Car details:");
    System.Console.WriteLine("make = " + make);
    System.Console.WriteLine("model = " + model);
    System.Console.WriteLine("color = " + color);
    System.Console.WriteLine("yearBuilt = " + yearBuilt);
  }
}

public class Example5_11
{
  public static void Main()
  {
    // create a Car object using the constructor
    // defined in the class
    Car myCar = new Car("Toyota", "MR2", "black", 1995);
    // display the values for the Car object fields
    myCar.Display();
  }
}


Illustrates overloaded constructors

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/

/*
  Example5_12.cs illustrates overloaded constructors
*/

// declare the Car class
class Car
{
  // declare the fields
  private string make;
  private string model;
  private string color;
  private int yearBuilt;
  // define the overloaded constructors
  public Car()
  {
    this.make = "Ford";
    this.model = "Mustang";
    this.color = "red";
    this.yearBuilt = 1970;
  }
  public Car(string make)
  {
    this.make = make;
    this.model = "Corvette";
    this.color = "silver";
    this.yearBuilt = 1969;
  }
  public Car(string make, string model, string color, int yearBuilt)
  {
    this.make = make;
    this.model = model;
    this.color = color;
    this.yearBuilt = yearBuilt;
  }
  // define method to display the fields
  public void Display()
  {
    System.Console.WriteLine("make = " + make);
    System.Console.WriteLine("model = " + model);
    System.Console.WriteLine("color = " + color);
    System.Console.WriteLine("yearBuilt = " + yearBuilt);
  }
}

public class Example5_12
{
  public static void Main()
  {
    // create three Car objects using the constructors
    // defined in the class
    Car myCar = new Car("Toyota", "MR2", "black", 1995);
    Car myCar2 = new Car();
    Car myCar3 = new Car("Chevrolet");
    // display the values for the Car object"s fields
    System.Console.WriteLine("myCar details:");
    myCar.Display();
    System.Console.WriteLine("myCar2 details:");
    myCar2.Display();
    System.Console.WriteLine("myCar3 details:");
    myCar3.Display();
  }
}


Shows the order in which constructors and destructors are called in a C# program

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Order.cs - shows the order in which constructors and destructors
//            are called in a C# program.
//
//            Compile this program with the following command line:
//                C:>csc Order.cs
//
namespace nsOrder
{
    using System;
    
    public class clsMainOrder
    {
        static public void Main ()
        {
            clsLastChild child = new clsLastChild ();
            Console.WriteLine ();
        }
    }
//
// Declare a base class and have its constructor and destructors
// print messages.
    class clsBase
    {
        public clsBase ()
        {
            Console.WriteLine ("Base class constructor called");
        }
        ~clsBase ()
        {
            Console.WriteLine ("Base class destructor called");
        }
    }
// Derive a class from clsBase. Have the constructor and destructor
// print messages.
    class clsFirstChild : clsBase
    {
        public clsFirstChild ()
        {
            Console.WriteLine ("First Child constructor called");
        }
        ~clsFirstChild ()
        {
            Console.WriteLine ("First Child destructor called");
        }
    }
// Derive a class from clsFirstChile. Have the constructor and destructor
// print messages as well.
    class clsLastChild  : clsFirstChild
    {
        public clsLastChild ()
        {
            Console.WriteLine ("Last Child constructor called");
        }
        ~clsLastChild ()
        {
            Console.WriteLine ("Last Child destructor called");
        }
    }
}