switch类型模式

  • switch的模式中有一种叫类型模式,可以根据switch的类型来执行对应的case,这点在代码中用到的比较频繁,特别是在对应同类型对象的操作中。本例是把一组数据,转成一种格式,就是很简单的使用switch类型模式实现,具体见代码:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace SwitchDemo;
  7. public class ClassOne
  8. {
  9. public void Run()
  10. {
  11. var entity = new YamlFormatCreater();
  12. var data = new Data();
  13. Console.WriteLine(GetData(entity, data));
  14. }
  15. public string GetDataFormat(IFormatCreater entity, Data data) => entity switch
  16. {
  17. CSVFormatCreater csvFormatCreater => csvFormatCreater.ToCSV(data),
  18. JsonFormatCreater jsonFormatCreater => jsonFormatCreater.ToJson(data),
  19. XMLFormatCreater xmlFormatCreater => xmlFormatCreater.ToXML(data),
  20. YamlFormatCreater yamlFormatCreater => yamlFormatCreater.ToYAML(data),
  21. _ => "this format is not adapted"
  22. };
  23. }
  24. public class Data
  25. {
  26. public int ID { get; set; }
  27. public string? Name { get; set; }
  28. public string? Model { get; set; }
  29. }
  30. public interface IFormatCreater
  31. { }
  32. public class CSVFormatCreater : IFormatCreater
  33. {
  34. public string ToCSV(Data data)
  35. {
  36. return "To CSV";
  37. }
  38. }
  39. public class JsonFormatCreater : IFormatCreater
  40. {
  41. public string ToJson(Data data)
  42. {
  43. return "To JSON";
  44. }
  45. }
  46. public class XMLFormatCreater : IFormatCreater
  47. {
  48. public string ToXML(Data data)
  49. {
  50. return "To XML";
  51. }
  52. }
  53. public class YamlFormatCreater : IFormatCreater
  54. {
  55. public string ToYAML(Data data)
  56. {
  57. return "To YAML";
  58. }
  59. }