类属性的定义与定义字段有些相似之处.但结构代码要多出不少.属性一般与一个私有字段相关联,以控制对这个字段的访问,此时get块可以直接返回该字段的值.
看代码示例:

  1. class MyBase
  2.     {
  3.         private int age;
  4.         public int Age
  5.         {
  6.             get
  7.             {
  8.                 return age;
  9.             }
  10.             set
  11.             {
  12.                 age = value;
  13.             }
  14.         }
  15.     }
  16.     class Program
  17.     {
  18.         static void Main(string[] args)
  19.         {
  20.             MyBase MyObj = new MyBase();
  21.             MyObj.Age = 20;
  22.             Console.WriteLine(MyObj.Age);
  23.             Console.ReadKey();
  24.         }
  25.     }

Read the rest of this entry »

, , , , ,

C#编程:定义类成员-定义方法
接着总结定义类成员-定义方法.定义方法通常有四个关键字.来决定方法的使用区域.
关键字:virtual, abstract:, override, extern, static
1.virtual:方法可以重写
2.abstract:只用于抽象类中重写
3.override:方法重写了一个基类的方法
4.extern:方法定义放在其它地方

定义方法实例:

  1. class MyClass
  2.     {
  3.         public string GetString()
  4.         {
  5.             return "here is a string.";
  6.         }
  7.     }

使用此方法:先实例化对象

  1. static void Main(string[] args)
  2.         {
  3.             MyClass MyObj = new MyClass();
  4.             Console.WriteLine(MyObj.GetString());
  5.             Console.ReadKey();
  6.         }

Read the rest of this entry »

, , , , , , ,