Csharp/C Sharp/Class Interface/Class Definition — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 11:39, 26 мая 2010
Содержание
- 1 A program that uses the Building class
- 2 A Simple C# Class
- 3 A simple inventory example
- 4 Assign value to class
- 5 Create class
- 6 Declare class and use it
- 7 Declaring and Defining Classes
- 8 Declaring Class Instances
- 9 Demonstrate the use of a nested class to contain data
- 10 Illustrates hiding
- 11 Illustrates how to assign default values to fields using initializers
- 12 Illustrates how to declare classes, object references, and create objects
- 13 illustrates how to use a "has a" relationship
- 14 Illustrates nested classes
- 15 Multiple constructors in a class definition
- 16 Return an object
- 17 Show name hiding in a derived class
- 18 simulate a bank account
- 19 This program creates two Building objects
- 20 Uses a class from Example16_3a.cs
- 21 Using Initializers
- 22 Variable in and out a class
A program that uses the Building class
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// A program that uses the Building class.
using System;
class Building {
public int floors; // number of floors
public int area; // total square footage of building
public int occupants; // number of occupants
}
// This class declares an object of type Building.
public class BuildingDemo {
public static void Main() {
Building house = new Building(); // create a Building object
int areaPP; // area per person
// assign values to fields in house
house.occupants = 4;
house.area = 2500;
house.floors = 2;
// compute the area per person
areaPP = house.area / house.occupants;
Console.WriteLine("house has:\n " +
house.floors + " floors\n " +
house.occupants + " occupants\n " +
house.area + " total area\n " +
areaPP + " area per person");
}
}
A Simple C# Class
using System;
public class ASimpleClass
{
public static void Main()
{
Point myPoint = new Point(10, 15);
Console.WriteLine("myPoint.x {0}", myPoint.x);
Console.WriteLine("myPoint.y {0}", myPoint.y);
}
}
class Point
{
// constructor
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
// member fields
public int x;
public int y;
}
A simple inventory example
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// A simple inventory example.
using System;
using System.Collections;
class Inventory {
string name;
double cost;
int onhand;
public Inventory(string n, double c, int h) {
name = n;
cost = c;
onhand = h;
}
public override string ToString() {
return
String.Format("{0,-10}Cost: {1,6:C} On hand: {2}",
name, cost, onhand);
}
}
public class InventoryList {
public static void Main() {
ArrayList inv = new ArrayList();
// Add elements to the list
inv.Add(new Inventory("Pliers", 5.95, 3));
inv.Add(new Inventory("Wrenches", 8.29, 2));
inv.Add(new Inventory("Hammers", 3.50, 4));
inv.Add(new Inventory("Drills", 19.88, 8));
Console.WriteLine("Inventory list:");
foreach(Inventory i in inv) {
Console.WriteLine(" " + i);
}
}
}
Assign value to class
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// This program will not compile.
class X {
int a;
public X(int i) { a = i; }
}
class Y {
int a;
public Y(int i) { a = i; }
}
public class IncompatibleRef {
public static void Main() {
X x = new X(10);
X x2;
Y y = new Y(5);
x2 = x; // OK, both of same type
x2 = y; // Error, not of same type
}
}
Create class
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
public class MyTime
{
// private variables
private int year;
private int month;
private int date;
private int hour;
private int minute;
private int second;
// public methods
public void DisplayCurrentMyTime()
{
Console.WriteLine(
"stub for DisplayCurrentMyTime");
}
}
public class Tester
{
static void Main()
{
MyTime timeObject = new MyTime();
timeObject.DisplayCurrentMyTime();
}
}
Declare class and use it
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System;
class Rect {
public int width;
public int height;
public Rect(int w, int h) {
width = w;
height = h;
}
public int area() {
return width * height;
}
}
public class UseRect {
public static void Main() {
Rect r1 = new Rect(4, 5);
Rect r2 = new Rect(7, 9);
Console.WriteLine("Area of r1: " + r1.area());
Console.WriteLine("Area of r2: " + r2.area());
}
}
Declaring and Defining Classes
/*
* 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 DeclaringandDefiningClasses
{
static private int MyInt = 5;
static public int MyInt2 = 10;
static public int[] MyIntArray;
static private int ObjectCount = 0;
static void Main(string[] args)
{
MyIntArray = new int[10];
ObjectCount++;
}
public static int MyMethod(int myInt)
{
MyInt = MyInt + myInt;
return MyInt;
}
private static long MyLongMethod(ref int myInt)
{
return myInt;
}
}
}
Declaring Class Instances
/*
* 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 DeclaringClassInstances
{
static void Main(string[] args)
{
ClassInstantied MyClass = new ClassInstantied();
}
}
class ClassInstantied
{
public void Display()
{
Console.WriteLine("Hello World");
}
}
}
Demonstrate the use of a nested class to contain data
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// Nested.cs -- demonstrate the use of a nested class to contain data
//
// Compile this program with the following command line
// C:>csc Nested.cs
//
namespace nsReadOnly
{
using System;
public class Nested
{
static double DegreeFactor = 1;
static double MilFactor = 0.05625;
static double RadianFactor = 57.29578;
static public void Main ()
{
double angle = 90;
double radius = 50;
// Declare an instance of the nested class
clsArea.clsData data = new clsArea.clsData (angle, radius,
DegreeFactor);
clsArea InDegrees = new clsArea (data);
// Change the values to mils
data.Factor = MilFactor;
data.Angle = angle * 17.77778;
clsArea InMils = new clsArea (data);
// Change the values to radians
data.Angle = angle / 57.29578;
data.Factor = RadianFactor;
clsArea InRadians = new clsArea (data);
Console.WriteLine ("Area of pie of {0,0:F3} degrees is {1,0:F1}",
InDegrees.Data.Angle, InDegrees.Area);
Console.WriteLine ("Area of pie of {0,0:F3} radians is {1,0:F1}",
InRadians.Data.Angle, InRadians.Area);
Console.WriteLine ("Area of pie of {0,0:F3} mils is {1,0:F1}",
InMils.Data.Angle, InMils.Area);
}
}
class clsArea
{
public class clsData : ICloneable
{
public clsData (double angle, double radius, double factor)
{
m_Angle = angle;
m_Radius = radius;
m_Factor = factor / 57.29578;
}
public double Angle
{
get {return(m_Angle);}
set {m_Angle = value;}
}
public double Radius
{
get {return(m_Radius);}
set {m_Radius = value;}
}
public double Factor
{
get {return(m_Factor);}
set {m_Factor = value / 57.29578;}
}
private double m_Angle = 0;
private double m_Radius = 0;
private double m_Factor = 1;
public object Clone ()
{
clsData clone = new clsData (m_Angle, m_Radius,
m_Factor * 57.29578);
return (clone);
}
}
public clsArea (clsData data)
{
// Clone the data object to get a copy for ourselves
m_Data = (clsData) data.Clone();
}
public clsData Data
{
get {return (m_Data);}
}
private clsData m_Data;
private const double pi = 3.14159;
private const double radian = 57.29578;
public double Area
{
get
{
return (m_Data.Radius * m_Data.Radius * pi
* m_Data.Angle * m_Data.Factor / (2 * pi));
}
}
}
}
Illustrates hiding
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example5_4.cs illustrates hiding
*/
// declare the Car class
class Car
{
public int yearBuilt;
public double maximumSpeed;
public int Age(int currentYear)
{
int maximumSpeed = 100; // hides the field
System.Console.WriteLine("In Age(): maximumSpeed = " +
maximumSpeed);
int age = currentYear - yearBuilt;
return age;
}
public double Distance(double initialSpeed, double time)
{
System.Console.WriteLine("In Distance(): maximumSpeed = " +
maximumSpeed);
return (initialSpeed + maximumSpeed) / 2 * time;
}
}
public class Example5_4
{
public static void Main()
{
// create a Car object
Car redPorsche = new Car();
redPorsche.yearBuilt = 2000;
redPorsche.maximumSpeed = 150;
int age = redPorsche.Age(2001);
System.Console.WriteLine("redPorsche is " + age + " year old.");
System.Console.WriteLine("redPorsche travels " +
redPorsche.Distance(31, .25) + " miles.");
}
}
Illustrates how to assign default values to fields using initializers
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example5_2.cs illustrates how to assign default values
to fields using initializers
*/
// declare the Car class
class Car
{
// declare the fields
public string make = "Ford";
public string model = "T";
public string color; // default value of null
public int yearBuilt = 1910;
// define the methods
public void Start()
{
System.Console.WriteLine(model + " started");
}
public void Stop()
{
System.Console.WriteLine(model + " stopped");
}
}
public class Example5_2
{
public static void Main()
{
// create a Car object
Car myCar = new Car();
// display the default values for the Car object fields
System.Console.WriteLine("myCar.make = " + myCar.make);
System.Console.WriteLine("myCar.model = " + myCar.model);
if (myCar.color == null)
{
System.Console.WriteLine("myCar.color is null");
}
System.Console.WriteLine("myCar.yearBuilt = " + myCar.yearBuilt);
}
}
Illustrates how to declare classes, object references, and create objects
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example5_1.cs illustrates how to declare
classes, object references, and create objects
*/
// declare the Car class
class Car
{
// declare the fields
public string make;
public string model;
public string color;
public int yearBuilt;
// define the methods
public void Start()
{
System.Console.WriteLine(model + " started");
}
public void Stop()
{
System.Console.WriteLine(model + " stopped");
}
}
public class Example5_1
{
public static void Main()
{
// declare a Car object reference named myCar
Car myCar;
// create a Car object, and assign its address to myCar
System.Console.WriteLine("Creating a Car object and assigning " +
"its memory location to myCar");
myCar = new Car();
// assign values to the Car object"s fields using myCar
myCar.make = "Toyota";
myCar.model = "MR2";
myCar.color = "black";
myCar.yearBuilt = 1995;
// display the field values using myCar
System.Console.WriteLine("myCar details:");
System.Console.WriteLine("myCar.make = " + myCar.make);
System.Console.WriteLine("myCar.model = " + myCar.model);
System.Console.WriteLine("myCar.color = " + myCar.color);
System.Console.WriteLine("myCar.yearBuilt = " + myCar.yearBuilt);
// call the methods using myCar
myCar.Start();
myCar.Stop();
// declare another Car object reference and
// create another Car object
System.Console.WriteLine("Creating another Car object and " +
"assigning its memory location to redPorsche");
Car redPorsche = new Car();
redPorsche.make = "Porsche";
redPorsche.model = "Boxster";
redPorsche.color = "red";
redPorsche.yearBuilt = 2000;
System.Console.WriteLine("redPorsche is a " + redPorsche.model);
// change the object referenced by the myCar object reference
// to the object referenced by redPorshe
System.Console.WriteLine("Assigning redPorsche to myCar");
myCar = redPorsche;
System.Console.WriteLine("myCar details:");
System.Console.WriteLine("myCar.make = " + myCar.make);
System.Console.WriteLine("myCar.model = " + myCar.model);
System.Console.WriteLine("myCar.color = " + myCar.color);
System.Console.WriteLine("myCar.yearBuilt = " + myCar.yearBuilt);
// assign null to myCar (myCar will no longer reference an object)
myCar = null;
}
}
illustrates how to use a "has a" relationship
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example6_5.cs illustrates how to use a "has a"
relationship
*/
// declare the Engine class
class Engine
{
// declare the fields
public int cylinders;
public int horsepower;
// define the method
public void Start()
{
System.Console.WriteLine("Engine started");
}
}
// declare the Car class
class Car
{
// declare the fields
public string make;
public Engine engine; // Car has an Engine
// define the method
public void Start()
{
engine.Start();
}
}
public class Example6_5
{
public static void Main()
{
// declare a Car object reference named myCar
System.Console.WriteLine("Creating a Car object");
Car myCar = new Car();
myCar.make = "Toyota";
// Car objects have an Engine object
System.Console.WriteLine("Creating an Engine object");
myCar.engine = new Engine();
myCar.engine.cylinders = 4;
myCar.engine.horsepower = 180;
// display the values for the Car and Engine object fields
System.Console.WriteLine("myCar.make = " + myCar.make);
System.Console.WriteLine("myCar.engine.cylinders = " +
myCar.engine.cylinders);
System.Console.WriteLine("myCar.engine.horsepower = " +
myCar.engine.horsepower);
// call the Car object"s Start() method
myCar.Start();
}
}
Illustrates nested classes
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example6_6.cs illustrates nested classes
*/
// declare the Car class
class Car
{
// declare the Engine class
public class Engine
{
// declare the Engine fields
public int cylinders;
public int horsepower;
// define the Engine method
public void Start()
{
System.Console.WriteLine("Engine started");
}
}
// declare the Car fields
public string make;
public Engine engine; // Car has an Engine
// define the Car method
public void Start()
{
engine.Start();
}
}
public class Example6_6
{
public static void Main()
{
// declare a Car object reference named myCar
System.Console.WriteLine("Creating a Car object");
Car myCar = new Car();
myCar.make = "Toyota";
// Car objects have an Engine object
System.Console.WriteLine("Creating an Engine object");
myCar.engine = new Car.Engine();
myCar.engine.cylinders = 4;
myCar.engine.horsepower = 180;
// display the values for the Car and Engine object fields
System.Console.WriteLine("myCar.make = " + myCar.make);
System.Console.WriteLine("myCar.engine.cylinders = " +
myCar.engine.cylinders);
System.Console.WriteLine("myCar.engine.horsepower = " +
myCar.engine.horsepower);
// call the Car object"s Start() method
myCar.Start();
}
}
Multiple constructors in a class definition
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Constrct.cs - Demonstrates the use of multiple constructors
// in a class definition.
//
// Compile this program with the following command line:
// C:>csc Constrct.cs
//
namespace nsConstructor
{
using System;
struct POINT
{
public POINT (int cx, int cy)
{
this.cx = cx;
this.cy = cy;
}
public int cx;
public int cy;
}
public class Constrct
{
static public void Main ()
{
clsRect rc1 = new clsRect();
clsRect rc2 = new clsRect (10, 12, 84, 96);
POINT pt1 = new POINT (10, 12);
POINT pt2 = new POINT (84, 96);
clsRect rc3 = new clsRect (pt1, pt2);
}
}
class clsRect
{
// The following constructor replaces the default constructor
public clsRect ()
{
Console.WriteLine ("Default constructor called");
m_Left = m_Top = m_Right = m_Bottom = 0;
}
public clsRect (int cx1, int cy1, int cx2, int cy2)
{
Console.WriteLine ("Constructor 1 called");
m_Left = cx1;
m_Top = cy1;
m_Right = cx2;
m_Bottom = cy2;
}
public clsRect (POINT pt1, POINT pt2)
{
Console.WriteLine ("Constructor 2 called");
m_Left = pt1.cx;
m_Top = pt1.cy;
m_Right = pt2.cx;
m_Bottom = pt2.cy;
}
public POINT UpperLeft
{
get {return(new POINT(m_Left, m_Top));}
set {m_Left = value.cx; m_Top = value.cy;}
}
public POINT LowerRight
{
get {return(new POINT(m_Right, m_Bottom));}
set {m_Right = value.cx; m_Bottom = value.cy;}
}
private int m_Left;
private int m_Top;
private int m_Right;
private int m_Bottom;
}
}
Return an object
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Return an object.
using System;
class Rect {
int width;
int height;
public Rect(int w, int h) {
width = w;
height = h;
}
public int area() {
return width * height;
}
public void show() {
Console.WriteLine(width + " " + height);
}
/* Return a rectangle that is a specified
factor larger than the invoking rectangle. */
public Rect enlarge(int factor) {
return new Rect(width * factor, height * factor);
}
}
public class RetObj {
public static void Main() {
Rect r1 = new Rect(4, 5);
Console.Write("Dimensions of r1: ");
r1.show();
Console.WriteLine("Area of r1: " + r1.area());
Console.WriteLine();
// create a rectange that is twice as big as r1
Rect r2 = r1.enlarge(2);
Console.Write("Dimensions of r2: ");
r2.show();
Console.WriteLine("Area of r2 " + r2.area());
}
}
Show name hiding in a derived class
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// Hide.cs -- Show name hiding in a derived class
//
// Compile this program with the following command line:
// C:>csc Hide.cs
//
namespace nsHide
{
using System;
using System.Reflection;
public class Hide
{
static public void Main ()
{
clsBase Base = new clsBase();
clsDerived Derived = new clsDerived ();
Base.x = 42;
Derived.x = 42;
Console.WriteLine ("For the base class:");
Console.WriteLine ("\tThe type stored in clsBase is " + Base.TypeOf());
Console.WriteLine ("\tMathOp () returns {0,0:F3} for {1}", Base.MathOp(42), 42);
Console.WriteLine ("\r\nFor the derived class:");
Console.WriteLine ("\tThe type stored in clsDerived is " + Derived.TypeOf());
Console.WriteLine ("\tMathOp () returns {0,0:F3} for {1}", Derived.MathOp(42), 42);
}
}
class clsBase
{
protected int m_x;
public int x
{
get {return (x);}
set {m_x = value;}
}
public double MathOp (int val)
{
return (Math.Sqrt ((double) val));
}
public string TypeOf ()
{
return ("integer");
}
}
class clsDerived : clsBase
{
new protected double m_x;
new public double x
{
get {return (x);}
set {m_x = value;}
}
new public double MathOp (int val)
{
return ((double) (val * val));
}
new public string TypeOf ()
{
return ("long");
}
}
}
simulate a bank account
using System;
public class BankAccount {
public static int nNextAccountNumber = 1000;
public int nAccountNumber;
public double dBalance;
public void InitBankAccount() {
nAccountNumber = ++nNextAccountNumber;
dBalance = 0.0;
}
public void Deposit(double dAmount) {
if (dAmount > 0.0) {
dBalance += dAmount;
}
}
public double Withdraw(double dWithdrawal) {
if (dBalance <= dWithdrawal) {
dWithdrawal = dBalance;
}
dBalance -= dWithdrawal;
return dWithdrawal;
}
}
This program creates two Building objects
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// This program creates two Building objects.
using System;
class Building {
public int floors; // number of floors
public int area; // total square footage of building
public int occupants; // number of occupants
}
// This class declares two objects of type Building.
public class BuildingDemo1 {
public static void Main() {
Building house = new Building();
Building office = new Building();
int areaPP; // area per person
// assign values to fields in house
house.occupants = 4;
house.area = 2500;
house.floors = 2;
// assign values to fields in office
office.occupants = 25;
office.area = 4200;
office.floors = 3;
// compute the area per person in house
areaPP = house.area / house.occupants;
Console.WriteLine("house has:\n " +
house.floors + " floors\n " +
house.occupants + " occupants\n " +
house.area + " total area\n " +
areaPP + " area per person");
Console.WriteLine();
// compute the area per person in office
areaPP = office.area / office.occupants;
Console.WriteLine("office has:\n " +
office.floors + " floors\n " +
office.occupants + " occupants\n " +
office.area + " total area\n " +
areaPP + " area per person");
}
}
Uses a class from Example16_3a.cs
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example16_3b.cs uses a class from Example16_3a.cs
*/
using System;
using StringSwitch; // name space define in Example16_3c.cs
public class Example16_3b
{
public static void Main()
{
string localString;
MySwitch s = new MySwitch();
s.inString="abcdef";
s.upper(out localString);
Console.WriteLine(localString);
}
}
//===========================================================
/*
Example16_3c.cs provides manifest information for Example 16_3
*/
using System.Reflection;
[assembly: AssemblyTitle("Example 16.3")]
[assembly: AssemblyVersion("1.0.0.0")]
//===========================================================
/*
Example16_3a.cs creates a namespace with a single class
*/
using System;
namespace StringSwitch
{
class MySwitch
{
string privateString;
public string inString
{
get
{
return privateString;
}
set
{
privateString = value;
}
}
public void upper(out string upperString)
{
upperString = privateString.ToUpper();
}
}
}
Using Initializers
public class Product {
public string make = "Ford";
public string model = "T";
public string color; // default value of null
public int yearBuilt = 1910;
public void Start() {
System.Console.WriteLine(model + " started");
}
public void Stop() {
System.Console.WriteLine(model + " stopped");
}
}
class MainClass {
public static void Main() {
Product myProduct = new Product();
System.Console.WriteLine("myProduct.make = " + myProduct.make);
System.Console.WriteLine("myProduct.model = " + myProduct.model);
if (myProduct.color == null) {
System.Console.WriteLine("myProduct.color is null");
}
System.Console.WriteLine("myProduct.yearBuilt = " + myProduct.yearBuilt);
}
}
Variable in and out a class
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
namespace heap
{
public class Dog
{
public int weight;
}
public class TesterClass
{
public void Run()
{
// create an integer
int firstInt = 5;
// create a second integer
int secondInt = firstInt;
// display the two integers
Console.WriteLine("firstInt: {0} secondInt: {1}",
firstInt, secondInt);
// modify the second integer
secondInt = 7;
// display the two integers
Console.WriteLine("firstInt: {0} secondInt: {1}",
firstInt, secondInt);
// create a dog
Dog milo = new Dog();
// assign a value to weight
milo.weight = 5;
// create a second reference to the dog
Dog fido = milo;
// display their values
Console.WriteLine("Milo: {0}, fido: {1}",
milo.weight, fido.weight);
// assign a new weight to the second reference
fido.weight = 7;
// display the two values
Console.WriteLine("Milo: {0}, fido: {1}",
milo.weight, fido.weight);
}
static void Main()
{
TesterClass t = new TesterClass();
t.Run();
}
}
}