Csharp/CSharp Tutorial/Class/Properties — различия между версиями

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

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

Add Length property to MyArray

using System; 
 
class MyArray {  
  int[] a;
  int len;
 
  public bool errflag; 
   
  public MyArray(int size) { 
    a = new int[size]; 
    len = size;  
  } 
 
  public int Length { 
    get { 
      return len; 
    } 
  } 
 
  public int this[int index] { 
    get { 
      if(indexCheck(index)) { 
        errflag = false; 
        return a[index]; 
      } else { 
        errflag = true; 
        return 0; 
      } 
    } 
 
    set { 
      if(indexCheck(index)) { 
        a[index] = value; 
        errflag = false; 
      } 
      else errflag = true; 
    } 
  } 
 
  private bool indexCheck(int index) { 
   if(index >= 0 & index < Length) 
      return true; 
   return false; 
  } 
}  
  
class MainClass {  
  public static void Main() {  
    MyArray myArray = new MyArray(5); 
    int x; 
 
    for(int i=0; i < myArray.Length; i++) 
      myArray[i] = i*10; 
 
    for(int i=0; i < myArray.Length; i++) { 
      x = myArray[i]; 
      if(x != -1) Console.Write(x + " "); 
    } 
    Console.WriteLine(); 
  } 
}
0 10 20 30 40

Add statement to the getter and setter of a property

public class A
{
   private int myValue;
   public int MyValue
   {
      get
      {
         System.Console.WriteLine( "Getting myValue" );
         return myValue;
      }
      set
      {
         System.Console.WriteLine( "Setting myValue" );
         myValue = value;
      }
   }
}
public class MainClass
{
   static void Main()
   {
      A obj = new A();
      obj.MyValue = 1;
      System.Console.WriteLine( "obj.Value = {0}",
                                obj.MyValue );
   }
}
Setting myValue
Getting myValue
obj.Value = 1

A simple property example

using System; 
 
class SimpProp {  
  int prop; 
 
  public SimpProp() { 
     prop = 0; 
  } 
 
  public int MyProp { 
    get { 
      return prop; 
    } 
    set { 
      prop = value; 
    }  
  } 
}  
  
class MainClass {  
  public static void Main() {  
    SimpProp ob = new SimpProp(); 
 
    Console.WriteLine("Original value of ob.MyProp: " + ob.MyProp); 
 
    ob.MyProp = 100;
    Console.WriteLine("Value of ob.MyProp: " + ob.MyProp); 
 
    Console.WriteLine("Attempting to assign -10 to ob.MyProp"); 
    ob.MyProp = -10; 
    Console.WriteLine("Value of ob.MyProp: " + ob.MyProp); 
  } 
}
Original value of ob.MyProp: 0
Value of ob.MyProp: 100
Attempting to assign -10 to ob.MyProp
Value of ob.MyProp: -10

Combine readonly and read only property

using System;
public sealed class Value
{
    public int intValue = 10;
}
public sealed class MyController
{
    public MyController( Value pimpl ) {
        this.pimpl = pimpl;
    }
    public int IntValue {
        get {
            return pimpl.intValue;
        }
    }
    private readonly Value pimpl;
}
public sealed class MainClass
{
    static void Main() {
        Value someNumber = new Value( );
    }
}

Define accessors for Properties with get and set

class MyClass
{
    private string name;
    
    public string Name
    {
        get 
        {
            return name;
        }
        set 
        {
            name = value;
        }
    }
}

Do calculation with Property

using System;
public class SomeClass
{
    private int num;
    public SomeClass(int i)
    {
        num = i;
    }
    public int Num
    {
        get { return num; }
        set { num = value; }
    }
}
   
public class CompoundAssPropApp
{
    public static void Main(string[] args)
    {
        SomeClass sc = new SomeClass(42);
        Console.WriteLine("{0}", sc.Num);
        
        sc.Num = sc.Num + 5;
        Console.WriteLine("{0}", sc.Num);
    }
}

Invoke Indexed Property Demo

using System;
using System.Reflection;
using System.Globalization;
  class Class1
  {
  
  
    DateTime[] dateTimes = new DateTime[10];
    public DateTime this[int index]
    {
      get{ return dateTimes[index]; }
      set{ dateTimes[index] = value;}
    }
    
    
    private DateTime dateOfBirth;
    public DateTime DateOfBirth
    {
        get{ return dateOfBirth; }
        set{ dateOfBirth = value; }
    }
      
    public void Test()
    {
      Console.WriteLine("Test method called");
    }
    
    
    private string field;
    
    public string Property
    { 
      get{ return field; }
      set{ field = value; }
    }
    
  }

    class MainClass{
    
    static void Main(string[] args)
    {
      Type type = typeof(Class1);
      Console.WriteLine(type.FullName);
      
      object o = Activator.CreateInstance(type);
      type.InvokeMember( "Item", 
        BindingFlags.Instance | 
        BindingFlags.SetProperty | BindingFlags.Public, 
        null, o, new object[]{0, new DateTime(1966, 2, 12)});
        
      Console.WriteLine(((Class1)o)[0].ToString());
    }
    }

Properties and its Restrictions

  1. A property consists of a name along with get and set accessors.
  2. The accessors are used to get and set the value of a variable.

The general form of a property is shown here:


type propertyName {
        get {
            // get accessor code
        }
        
        set {
            // set accessor code
        }
    }
  1. A property cannot be passed as a ref or out parameter to a method.
  2. You cannot overload a property.
  3. A property should not alter the state of the underlying variable when the get accessor is called.

(Quote from C# The Complete Reference, Publisher: Osborne/McGraw-Hill, March 8, 2002, Language: English ISBN-10: 0072134852 ISBN-13: 978-0072134858)

Property And its associated Field

using System;

class MyClass
{
   private int privateInnerValue = 10; 
   public int MyValue                  
   {
      set { 
         privateInnerValue = value; 
      }
      get { 
         return privateInnerValue; 
      } 
   }
}
class MainClass
{
   static void Main()
   {
      MyClass c = new MyClass();
      Console.WriteLine("MyValue: {0}", c.MyValue);
      c.MyValue = 20;
      Console.WriteLine("MyValue: {0}", c.MyValue);
   }
}
MyValue: 10
MyValue: 20

Property Getter and Setter

using System;
   
class Address
{
    protected string city;
    public string City
    { 
     get { return city; }
    }
   
    protected string zipCode;
    public string ZipCode
    {
        get { return zipCode; }
        set 
        { 
            zipCode = value; 
            city = "Atlanta";
        }
    }
}
   
class PropertyApp
{
    public static void Main()
    {
        Address addr = new Address();
        addr.ZipCode = "30338";
        string zip = addr.ZipCode;
   
        Console.WriteLine("The city for ZIP code {0} is {1}", addr.ZipCode, addr.City);
    }
}

Put logic to property setter

using System;
using System.Collections.Generic;
using System.Text;
class MainClass
{
    static void Main(string[] args)
    {
        Person person = new Person();
        person.SetName("A", "B");
        Console.WriteLine("The person"s full name is {0}",person.FullName);
        person.FullName = "A b c";
        Console.WriteLine("The person"s full name is {0}",person.FullName);
    }
}
class Person
{
    private string _lastname;
    private string _firstname;
    public void SetName(string lastname, string firstname)
    {
        _lastname = lastname;
        _firstname = firstname;
    }
    public string FullName
    {
        get
        {
            return _firstname + " " + _lastname;
        }
        set
        {
            string[] names = value.Split(new string[] { " " },StringSplitOptions.RemoveEmptyEntries);
            _firstname = names[0];
            _lastname = names[names.Length - 1];
        }
    }
}
The person"s full name is B A
The person"s full name is A c

Readonly property

using System;
class MyClass
{
   public double A = 3;
   public double B = 4;
   
   public double MyValue                            
   {
      get { return A * B ; }     
   }
}
class MainClass
{
   static void Main()
   {
      MyClass c = new MyClass();
      Console.WriteLine("MyValue: {0}", c.MyValue);
   }
}
MyValue: 12

throw Exception from property setting

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

    public class MyClass
    {
        public readonly string Name;
        private int intVal;
        public int Val
        {
            get
            {
                return intVal;
            }
            set
            {
                if (value >= 0 && value <= 10)
                    intVal = value;
                else
                    throw (new ArgumentOutOfRangeException("Val", value,"Val must be assigned a value between 0 and 10."));
            }
        }
        public override string ToString()
        {
            return "Name: " + Name + "\nVal: " + Val;
        }
        private MyClass() : this("Default Name")
        {
        }
        public MyClass(string newName)
        {
            Name = newName;
            intVal = 0;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myObj = new MyClass("My Object");
            Console.WriteLine("myObj created.");
            for (int i = -1; i <= 0; i++)
            {
                try
                {
                    myObj.Val = i;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception {0} thrown.", e.GetType().FullName);
                    Console.WriteLine("Message:\n\"{0}\"", e.Message);
                }
            }
        }
    }

Use properties to set and get private members.

using System; 
 
class Shape { 
  double pri_width;  // now private 
  double pri_height; // now 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); 
  } 
} 
 
class Triangle : Shape { 
  public string style; // style of triangle 
   
  public double area() { 
    return width * height / 2;  
  } 
 
  public void showStyle() { 
    Console.WriteLine("Triangle is " + style); 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    Triangle t1 = new Triangle(); 
    Triangle t2 = new Triangle(); 
 
    t1.width = 4.0; 
    t1.height = 4.0; 
    t1.style = "isosceles"; 
 
    t2.width = 8.0; 
    t2.height = 12.0; 
    t2.style = "right"; 
 
    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