C# abstract修饰符浅析

来源:互联网 发布:qq软件测试报告范例 编辑:程序博客网 时间:2024/04/26 04:42

C#语言有很多值得学习的地方,这里我们主要介绍C# abstract修饰符,包括介绍通常用于强制继承类必须实现某一成员。等方面。

C# abstract修饰符是什么意思?

C# abstract修饰符可以用于类、方法、属性、事件和索引指示器(indexer),表示其为抽象成员 abstract 不可以和 static 、virtual 一起使用声明为 abstract 成员可以不包括实现代码,但只要类中还有未实现的抽象成员(即抽象类),那么它的对象就不能被实例化,通常用于强制继承类必须实现某一成员。

示例:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4.    
  5. namespace Example04  
  6. {  
  7. #region 基类,抽象类  
  8. public abstract class BaseClass  
  9. {  
  10. //抽象属性,同时具有get和set访问器表示继承类必须将该属性实现为可读写  
  11. public abstract String Attribute  
  12. {  
  13. get;  
  14. set;  
  15. }  
  16.    
  17. //抽象方法,传入一个字符串参数无返回值  
  18. public abstract void Function(String value);  
  19.    
  20. //抽象事件,类型为系统预定义的代理(delegate):EventHandler  
  21. public abstract event EventHandler Event;  
  22.    
  23. //抽象索引指示器,只具有get访问器表示继承类必须将该索引指示器实现为只读  
  24. public abstract Char this[int Index]  
  25. {  
  26. get;  
  27. }  
  28. }  
  29. #endregion  
  30.    
  31. #region 继承类  
  32. public class DeriveClass : BaseClass  
  33. {  
  34. private String attribute;  
  35.    
  36. public override String Attribute  
  37. {  
  38. get  
  39. {  
  40. return attribute;  
  41. }  
  42. set  
  43. {  
  44. attribute = value;  
  45. }  
  46. }  
  47. public override void Function(String value)  
  48. {  
  49. attribute = value;  
  50. if (Event != null)  
  51. {  
  52. Event(this, new EventArgs());  
  53. }  
  54. }  
  55. public override event EventHandler Event;  
  56. public override Char this[int Index]  
  57. {  
  58. get  
  59. {  
  60. return attribute[Index];  
  61. }  
  62. }  
  63. }  
  64. #endregion  
  65.    
  66. class Program  
  67. {  
  68. static void OnFunction(object sender, EventArgs e)  
  69. {  
  70. for (int i = 0; i < ((DeriveClass)sender).Attribute.Length; i++)  
  71. {  
  72. Console.WriteLine(((DeriveClass)sender)[i]);  
  73. }  
  74. }  
  75. static void Main(string[] args)  
  76. {  
  77. DeriveClass tmpObj = new DeriveClass();  
  78.    
  79. tmpObj.Attribute = "1234567";  
  80. Console.WriteLine(tmpObj.Attribute);  
  81.    
  82. //将静态函数OnFunction与tmpObj对象的Event事件进行关联  
  83. tmpObj.Event += new EventHandler(OnFunction);  
  84.    
  85. tmpObj.Function("7654321");  
  86.    
  87. Console.ReadLine();  
  88. }  
  89. }  
原创粉丝点击