给枚举增加扩展方法

作者:追风剑情 发布于:2017-9-30 17:10 分类:C#

示例: 扩展方法

  1. using System;
  2. using System.IO;
  3.  
  4. namespace EnumTest1
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. FileAttributes fa = FileAttributes.System;
  11. fa = fa.Set(FileAttributes.ReadOnly);
  12. fa = fa.Clear(FileAttributes.System);
  13. fa.ForEach(f=>Console.WriteLine(f));
  14.  
  15. Console.ReadLine();
  16. }
  17. }
  18.  
  19. internal static class FileAttributesExtensionMethods
  20. {
  21. public static Boolean IsSet(this FileAttributes flags, FileAttributes flagToTest)
  22. {
  23. if (flagToTest == 0)
  24. throw new ArgumentOutOfRangeException("flagToTest", "Value must not be 0");
  25. return (flags & flagToTest) == flagToTest;
  26. }
  27.  
  28. public static Boolean IsClear(this FileAttributes flags, FileAttributes flagToTest)
  29. {
  30. if(flagToTest == 0)
  31. throw new ArgumentOutOfRangeException("flagToTest", "Value must not be 0");
  32. return !IsSet(flags, flagToTest);
  33. }
  34.  
  35. public static Boolean AnyFlagsSet(this FileAttributes flags, FileAttributes testFlags)
  36. {
  37. return (flags & testFlags) != 0;
  38. }
  39.  
  40. public static FileAttributes Set(this FileAttributes flags, FileAttributes setFlags)
  41. {
  42. return flags | setFlags;
  43. }
  44.  
  45. public static FileAttributes Clear(this FileAttributes flags, FileAttributes clearFlags)
  46. {
  47. return flags & ~clearFlags;
  48. }
  49.  
  50. public static void ForEach(this FileAttributes flags, Action<FileAttributes> processFlag)
  51. {
  52. if (processFlag == null)
  53. throw new ArgumentNullException("processFlag");
  54. for(UInt32 bit = 1; bit != 0; bit <<= 1)
  55. {
  56. UInt32 temp = ((UInt32)flags) & bit;
  57. if (temp != 0)
  58. processFlag((FileAttributes)temp);
  59. }
  60. }
  61. }
  62. }

运行测试

11111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号