Csharp/CSharp Tutorial/Class/Class Definition

Материал из .Net Framework эксперт
Версия от 12:16, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A simple, but complete, C# class.

using System;
class MainClass {
    MainClass() {
        Console.WriteLine("MainClass Constructor Called");
    }
    ~MainClass() {
        Console.WriteLine("MainClass Destructor Called");
    }
    void PrintAMessage(string msg) {
        Console.WriteLine("PrintAMessage: {0}", msg);
    }
    void Dispose() {
        GC.SuppressFinalize(this);
    }
    static void Main() {
        Console.WriteLine("Top of function main");
        MainClass app = new MainClass();
        app.PrintAMessage("Hello from class");
        Console.WriteLine("Bottom of function main");
        app.Dispose();
    }
}

A Simple Class showing class definition syntax

class MyClass
{
    int simpleValue = 0;
}

A Simple Class with member fields and constrctor

using System;
class Point
{
    // constructor
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
    
    // member fields
    public int x;
    public int y;
}
class MainClass
{
    public static void Main()
    {
        Point myPoint = new Point(10, 15);
        Console.WriteLine("myPoint.x {0}", myPoint.x);
        Console.WriteLine("myPoint.y {0}", myPoint.y);
    }
}
myPoint.x 10
myPoint.y 15

C# Accessibility Keywords

C# Access Modifier                       Meaning
public                                   Marks a member as accessible from an object variable and derived classes.
private                                  Marks a method as accessible only by the class that has defined the method. 
                                         In C#, all members are private by default.
protected                                Marks a method as usable by the defining class, and any derived classes. 
                                         Protected methods are not accessible from an object variable.
internal                                 Defines a method that is accessible by any type in the same assembly, but not outside the assembly.
protected internal                       Defines a method whose access is limited to the current assembly or types derived from the defining class in the current assembly.

Class can contain class

using System;
public class Car 
{
  private int maxSpeed;
  private Radio theMusicBox = new Radio();
  public Car()
  {
    maxSpeed = 100;
  }
  public void SwitchRadio(bool state)
  {
    theMusicBox.TurnOn(state);
  }
}
public class Radio
{
  public void TurnOn(bool on)
  {
    if(on)
      Console.WriteLine("ON...");
    else
      Console.WriteLine("OFF...");
  }
}
public class MainClass
{
  public static void Main(string[] args)
  {    
    // Make a car.
    Car c1 = new Car();
    c1.SwitchRadio(true);
    c1.SwitchRadio(false);
  }
}
ON...
OFF...

Class Fundamentals

  1. A class is a template that defines the form of an object.
  2. A class specifies both the data and the code that will operate on that data.
  3. Objects are instances of a class.
  4. The methods and variables that constitute a class are called members of the class.

7.1.Class Definition 7.1.1. Class Fundamentals 7.1.2. <A href="/Tutorial/CSharp/0140__Class/TheGeneralFormofaClass.htm">The General Form of a Class</a> 7.1.3. <A href="/Tutorial/CSharp/0140__Class/ASimpleClassshowingclassdefinitionsyntax.htm">A Simple Class showing class definition syntax</a> 7.1.4. <A href="/Tutorial/CSharp/0140__Class/AsimplebutcompleteCclass.htm">A simple, but complete, C# class.</a> 7.1.5. <A href="/Tutorial/CSharp/0140__Class/ASimpleClasswithmemberfieldsandconstrctor.htm">A Simple Class with member fields and constrctor</a> 7.1.6. <A href="/Tutorial/CSharp/0140__Class/DeclareanobjectoftypeBuilding.htm">Declare an object of type Building</a> 7.1.7. <A href="/Tutorial/CSharp/0140__Class/Createtwoobjectsforoneclass.htm">Create two objects for one class</a> 7.1.8. <A href="/Tutorial/CSharp/0140__Class/Copyaclass.htm">Copy a class</a> 7.1.9. <A href="/Tutorial/CSharp/0140__Class/Encapsulationexample.htm">Encapsulation example</a> 7.1.10. <A href="/Tutorial/CSharp/0140__Class/Classcancontainclass.htm">Class can contain class</a> 7.1.11. <A href="/Tutorial/CSharp/0140__Class/Inheritedmembermethodsandfields.htm">Inherited member methods and fields</a> 7.1.12. <A href="/Tutorial/CSharp/0140__Class/ReferencetoBaseClass.htm">Reference to Base Class</a> 7.1.13. <A href="/Tutorial/CSharp/0140__Class/Implementmultipleinterfaces.htm">Implement multiple interfaces</a> 7.1.14. <A href="/Tutorial/CSharp/0140__Class/Extendsclassandimplementsinterface.htm">Extends class and implements interface</a> 7.1.15. <A href="/Tutorial/CSharp/0140__Class/CAccessibilityKeywords.htm">C# Accessibility Keywords</a> 7.1.16. <A href="/Tutorial/CSharp/0140__Class/Themodifierscanbeappliedtomembersoftypesandhavevarioususes.htm">The modifiers can be applied to members of types, and have various uses.</a> 7.1.17. <A href="/Tutorial/CSharp/0140__Class/ValueTypesclassvsstruct.htm">Value Types: class vs struct</a>

Copy a class

using System; 
 
class MyClass { 
  public int x; 
} 
 
class MainClass { 
  public static void Main() { 
    MyClass a = new MyClass(); 
    MyClass b = new MyClass(); 
 
    a.x = 10; 
    b.x = 20; 
 
    Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x); 
 
    a = b; 
    b.x = 30; 
 
    Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x); 
  } 
}
a.x 10, b.x 20
a.x 30, b.x 30

Create two objects for one class

using System;  
  
class Building {   
  public int area;      
  public int occupants; 
}   
   
class BuildingDemo {   
  public static void Main() {   
    Building house = new Building();   
    Building office = new Building(); 
 
    int areaPP; // area per person 
   
    house.occupants = 4;  
    house.area = 2500;  
 
    office.occupants = 25;  
    office.area = 4200;  
   
    areaPP = house.area / house.occupants;  
   
    Console.WriteLine("house has:\n  " + 
                      house.occupants + " occupants\n  " + 
                      house.area + " total area\n  " + 
                      areaPP + " area per person"); 
 
    Console.WriteLine(); 
 
    areaPP = office.area / office.occupants;  
 
    Console.WriteLine("office has:\n  " + 
                      office.occupants + " occupants\n  " + 
                      office.area + " total area\n  " + 
                      areaPP + " area per person"); 
  }   
}
house has:
  4 occupants
  2500 total area
  625 area per person
office has:
  25 occupants
  4200 total area
  168 area per person

Declare an object of type Building

using System;  
  
class Building {   
  public int floors;    
  public int area;      
  public int occupants; 
}   
   
class BuildingDemo {   
  public static void Main() {   
    Building house = new Building(); // create a Building object 
    int areaPP; 
   
    house.occupants = 4;  
    house.area = 2500;  
    house.floors = 2;  
   
    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"); 
  }   
}
house has:
  2 floors
  4 occupants
  2500 total area
  625 area per person

Encapsulation example

class MyRectangle
{
   private uint width;
   private uint height;
   private uint area;
   public uint Width
   {
      get
      {
         return width;
      }
      set
      {
         width = value;
         ComputeArea();
      }
   }
   public uint Height
   {
      get
      {
         return height;
      }
      set
      {
         height = value;
         ComputeArea();
      }
   }
   public uint Area
   {
      get
      {
         return area;
      }
   }
   private void ComputeArea()
   {
      area = width * height;
   }
}

Extends class and implements interface

using System;
using System.Collections.Generic;
using System.Text;
interface Talkable
{
   string Table();
}
class Animal { }
class Cat : Animal, Talkable
{
   string Talkable.Table() { 
       return "miao"; 
   }
}
class Dog : Animal, Talkable
{
   string Talkable.Table(){ 
      return "bulk"; 
   }
}
class Elephant : Animal
{
    
}
class MainClass
{
   static void Main()
   {
      Animal[] AnimalArray = new Animal[3];
      AnimalArray[0] = new Cat();
      AnimalArray[1] = new Elephant();
      AnimalArray[2] = new Dog();
      foreach (Animal a in AnimalArray)
      {
         Talkable b = a as Talkable;
         if (b != null)
            Console.WriteLine("Baby is called: {0}", b.Table());
      }
   }
}
Baby is called: miao
Baby is called: bulk

Implement multiple interfaces

using System;
interface Getter { 
    int GetData(); 
}      
interface Setter { 
    void SetData(int x); 
}   
class MyData : Getter, Setter        
{
   int data; 
   public int GetData() { 
       return data; 
   }
   public void SetData(int x) { 
       data = x; 
   }
}
class MainClass
{
   static void Main()
   {
      MyData data = new MyData();
      data.SetData(5);
      Console.WriteLine("Value = {0}", data.GetData());
   }
}
Value = 5

Inherited member methods and fields

using System;
class BaseClass                           
{
   public string Field1 = "base class field";
   public void Method1(string value)
   {
      Console.WriteLine("Base class    -- Method1: {0}", value);
   }
}
class DerivedClass : BaseClass            
{
   public string Field2 = "derived class field";
   
   public void Method2(string value)
   {
      Console.WriteLine("Derived class -- Method2: {0}", value);
   }
}
class MainClass
{
   static void Main()
   {
      DerivedClass oc = new DerivedClass();
      oc.Method1(oc.Field1);               // Base method with base field
      oc.Method1(oc.Field2);               // Base method with derived field
      oc.Method2(oc.Field1);               // Derived method with base field
      oc.Method2(oc.Field2);               // Derived method with derived field
   }
}
Base class    -- Method1: base class field
Base class    -- Method1: derived class field
Derived class -- Method2: base class field
Derived class -- Method2: derived class field

Reference to Base Class

using System;
class BaseClass
{
   public void Print()
   {
      Console.WriteLine("This is the base class.");
   }
}
class DerivedClass : BaseClass
{
   new public void Print()
   {
      Console.WriteLine("This is the derived class.");
   }
}
class Program
{
   static void Main()
   {
      DerivedClass derived = new DerivedClass();
      BaseClass mybc = (BaseClass)derived;
      derived.Print();       
      mybc.Print();          
   }
}
This is the derived class.
This is the base class.

The General Form of a Class

A class is created by use of the keyword class.

The general form of a class definition that contains only instance variables and methods:


class classname {
    // declare instance variables
    access type var1;
    access type var2;
    // ...
    access type varN;
    
    // declare methods
    access ret-type method1(parameters) {
        // body of method
    }
    access ret-type method2(parameters) {
        // body of method
    }
    // ...
    access ret-type methodN(parameters) {
        // body of method
    }
}

The modifiers can be applied to members of types, and have various uses.

Modifier           Applies To                                       Description
new                Function members                                 hides an inherited member with the same signature.
static             All members                                      does not operate on a specific instance of the class.
virtual            Classes and function members only                can be overridden by a derived class.
abstract           Function members only                            A virtual member that defines the signature of the member, but doesn"t provide an implementation.
override           Function members only                            overrides an inherited virtual or abstract member.
sealed             Classes                                          overrides an inherited virtual member, but cannot be overridden by any classes that inherit from this class.
extern             static [DllImport] methods only                  implemented externally, in a different language.

Value Types: class vs struct

using System;
    class EntryPoint
    {
        static void Main(string[] args)
        {
            TemperatureStruct ts = new TemperatureStruct();
            TemperatureStruct tp = new TemperatureStruct();
            TemperatureClass tc = new TemperatureClass();
            Console.Write( "Enter degrees in Celsius: " );
            string celsius = Console.ReadLine();
            ts.Celsius = Convert.ToDouble(celsius);
            
            Console.WriteLine( "Temperature in Fahrenheit = {0}", ts.Fahrenheit );
        }
    }
    class TemperatureClass
    {
        private double degreesCelsius;
        public double Fahrenheit
        {
            get
            {
                return ((9d/5d)*degreesCelsius)+32;
            }
            set
            {
                degreesCelsius = (5d/9d)*(value-32);
            }
        }
        public double Celsius
        {
            get
            {
                return degreesCelsius;
            }
            set
            {
                degreesCelsius = value;
            }
        }
    }
    struct TemperatureStruct
    {
        public double Celsius;
        
        public double Fahrenheit
        {
            get
            {
                return ((9d/5d)*Celsius)+32;
            }
            set
            {
                Celsius = (5d/9d)*(value-32);
            }
        }
    }