Csharp/C Sharp/Class Interface/Class Variables

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

A Simple Class and Objects

 

public class Product {
    public string make;
    public string model;
    public string color;
    public int yearBuilt;
    public void Start() {
        System.Console.WriteLine(model + " started");
    }
    public void Stop() {
        System.Console.WriteLine(model + " stopped");
    }
}

class MainClass{
    public static void Main() {
        Product myProduct;
        myProduct = new Product();
        myProduct.make = "Toyota";
        myProduct.model = "MR2";
        myProduct.color = "black";
        myProduct.yearBuilt = 1995;
        System.Console.WriteLine("myProduct details:");
        System.Console.WriteLine("myProduct.make = " + myProduct.make);
        System.Console.WriteLine("myProduct.model = " + myProduct.model);
        System.Console.WriteLine("myProduct.color = " + myProduct.color);
        System.Console.WriteLine("myProduct.yearBuilt = " + myProduct.yearBuilt);
        myProduct.Start();
        myProduct.Stop();
        Product redPorsche = new Product();
        redPorsche.make = "Porsche";
        redPorsche.model = "Boxster";
        redPorsche.color = "red";
        redPorsche.yearBuilt = 2000;
        System.Console.WriteLine(          "redPorsche is a " + redPorsche.model);
        System.Console.WriteLine("Assigning redPorsche to myProduct");
        myProduct = redPorsche;
        System.Console.WriteLine("myProduct details:");
        System.Console.WriteLine("myProduct.make = " + myProduct.make);
        System.Console.WriteLine("myProduct.model = " + myProduct.model);
        System.Console.WriteLine("myProduct.color = " + myProduct.color);
        System.Console.WriteLine("myProduct.yearBuilt = " + myProduct.yearBuilt);
    }
}


Class variables with default value

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 public class MyTimeWithDefaultValue
 {
     // private member variables
     int year;
     int month;
     int date;
     int hour;
     int minute;
     int second = 30;
     // public method
     public void DisplayCurrentMyTimeWithDefaultValue()
     {
         System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}",
             month, date, year, hour, minute, second);
     }
     // constructor
     public MyTimeWithDefaultValue(int theYear, int theMonth, int theDate,
         int theHour, int theMinute)
     {
         year = theYear;
         month = theMonth;
         date = theDate;
         hour = theHour;
         minute = theMinute;
     }
 }
 public class Tester
 {
     static void Main()
     {
         MyTimeWithDefaultValue timeObject = new MyTimeWithDefaultValue(2005,3,25,9,35);
         timeObject.DisplayCurrentMyTimeWithDefaultValue();
     }
 }


declare a class Address containing the data members to describe a US address along with the member functions

 

using System;
class MainClass {
    public static void Main(string[] args) {
        Address addr = new Address();
        addr.SetStreet(123, "My Street");
        addr.SetCity("A", "X", 123456);
        Console.WriteLine(addr.GetStreetString());
        Console.WriteLine(addr.GetCityString());
        addr.Output();
    }
}
class Address {
    public int nAddressNumberPart;
    public string sAddressNamePart;
    public string sCity;
    public string sState;
    public int nPostalCode;
    public void SetStreet(int nNumber, string sName) {
        nAddressNumberPart = nNumber;
        sAddressNamePart = sName;
    }
    public string GetStreetString() {
        return nAddressNumberPart + " " + sAddressNamePart;
    }
    public void SetCity(string sCityIn, string sStateIn, int nPostalCodeIn) {
        sCity = sCityIn;
        sState = sStateIn;
        nPostalCode = nPostalCodeIn;
    }
    public string GetCityString() {
        return sCity + ", " + sState + " " + nPostalCode;
    }
    public string GetAddressString() {
        return GetStreetString() + "\n" + GetCityString();
    }
    public void Output() {
        Console.WriteLine(GetAddressString());
    }
}


Default Values of Class Member Variables

 
/*
    * bool types are set to false.
    * Numeric data is set to 0 (or 0.0 in the case of floating-point data types).
    * string types are set to null.
    * char types are set to "\0".
    * Reference types are set to null.
Given these rules, ponder the following code:
*/
class Test 
{ 
     public int myInt;        // Set to 0. 
     public string myString;  // Set to null. 
     public bool myBool;      // Set to false. 
     public object myObj;     // Set to null. 
}


Field Attributes

 
using System;
using System.Reflection;
public enum RegHives {
    HKEY_CLASSES_ROOT,
    HKEY_CURRENT_USER,
    HKEY_LOCAL_MACHINE,
    HKEY_USERS,
    HKEY_CURRENT_CONFIG
}
public class RegKeyAttribute : Attribute {
    public RegKeyAttribute(RegHives Hive, String ValueName) {
        this.Hive = Hive;
        this.ValueName = ValueName;
    }
    protected RegHives hive;
    public RegHives Hive {
        get { return hive; }
        set { hive = value; }
    }
    protected String valueName;
    public String ValueName {
        get { return valueName; }
        set { valueName = value; }
    }
}
class SomeClass {
    [RegKey(RegHives.HKEY_CURRENT_USER, "Foo")]
    public int Foo;
    public int Bar;
}
class Test {
    [STAThread]
    static void Main(string[] args) {
        Type type = Type.GetType("FieldAttribs.SomeClass");
        foreach (FieldInfo field in type.GetFields()) {
            foreach (Attribute attr in
                field.GetCustomAttributes(true)) {
                RegKeyAttribute rka =
                    attr as RegKeyAttribute;
                if (null != rka) {
                    Console.WriteLine("{0} will be saved in {1}\\\\{2}", field.Name, rka.Hive, rka.ValueName);
                }
            }
        }
    }
}


Static class variable

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 namespace Test_Console_App_3
 {
     // declare a Cat class
     // stripped down
     class Cat
     {
         // a private static member to keep
         // track of how many Cat objects have
         // been created
         private static int instances = 0;
         private int weight;
         private String name;
         // cat constructor
         // increments the count of Cats
         public Cat(String name, int weight)
         {
             instances++;
             this.name = name;
             this.weight = weight;
         }
         // Static method to retrieve
         // the current number of Cats
         public static void HowManyCats()
         {
             Console.WriteLine("{0} cats adopted",
                 instances);
         }
         public void TellWeight()
         {
             Console.WriteLine("{0} is {1} pounds",
                 name, weight);
         }
     }
    public class StaticInClassTester
    {
       public void Run()
       {
           Cat.HowManyCats();
           Cat frisky = new Cat("Frisky", 5);
           frisky.TellWeight();
           Cat.HowManyCats();
           Cat whiskers = new Cat("Whisky", 7);
           whiskers.TellWeight();
           Cat.HowManyCats();
       }
       static void Main()
       {
          StaticInClassTester t = new StaticInClassTester();
          t.Run();
       }
    }
 }


The super-string class.

 
using System;

public class MyString {
    private string fString;
    public MyString() {
        fString = "";
    }
    public MyString(string inStr) {
        fString = inStr;
    }
    public string ToStr() {
        return fString;
    }
    public string Right(int nChars) {
        if (nChars > fString.Length)
            return fString;
        string s = "";
        for (int i = fString.Length - nChars; i < fString.Length; ++i)
            s += fString[i];
        return s;
    }
    public string Left(int nChars) {
        if (nChars > fString.Length)
            return fString;
        string s = "";
        for (int i = 0; i < nChars; ++i)
            s += fString[i];
        return s;
    }
    public string Mid(int nStart, int nEnd) {
        if (nStart < 0 || nEnd > fString.Length)
            return fString;
        if (nStart > nEnd)
            return "";
        string s = "";
        for (int i = nStart; i < nEnd; ++i)
            s += fString[i];
        return s;
    }
}
class Class1 {
    static void Main(string[] args) {
        MyString s = new MyString("Hello world");
        System.Console.WriteLine("s = {0}", s.ToStr());
        System.Console.WriteLine("Right 3 = [{0}]", s.Right(3));
        System.Console.WriteLine("Left 6 = [{0}]", s.Left(6));
        System.Console.WriteLine("Mid 2,4 = [{0}]", s.Mid(2, 4));
    }
}