Fork me on GitHub

switch类型模式

  switch的模式中有一种叫类型模式,可以根据switch的类型来执行对应的case,这点在代码中用到的比较频繁,特别是在对应同类型对象的操作中。本例是把一组数据,转成一种格式,就是很简单的使用switch类型模式实现,具体见代码:

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

namespace SwitchDemo;

public class ClassOne
{
    public void Run()
    {
        var entity = new YamlFormatCreater();
        var data = new Data();
        Console.WriteLine(GetData(entity, data));
    }
    public string GetDataFormat(IFormatCreater entity, Data data) => entity switch
    {
        CSVFormatCreater csvFormatCreater => csvFormatCreater.ToCSV(data),
        JsonFormatCreater jsonFormatCreater => jsonFormatCreater.ToJson(data),
        XMLFormatCreater xmlFormatCreater => xmlFormatCreater.ToXML(data),
        YamlFormatCreater yamlFormatCreater => yamlFormatCreater.ToYAML(data),
        _ => "this format is not adapted"
    };
}

public class Data
{
    public int ID { get; set; }
    public string? Name { get; set; }
    public string? Model { get; set; }
}
public interface IFormatCreater
{ }

public class CSVFormatCreater : IFormatCreater
{
    public string ToCSV(Data data)
    {
        return "To CSV";
    }
}
public class JsonFormatCreater : IFormatCreater
{
    public string ToJson(Data data)
    {
        return "To JSON";
    }
}
public class XMLFormatCreater : IFormatCreater
{
    public string ToXML(Data data)
    {
        return "To XML";
    }
}
public class YamlFormatCreater : IFormatCreater
{
    public string ToYAML(Data data)
    {
        return "To YAML";
    }
}
 想要更快更方便的了解相关知识,可以关注微信公众号 
 
posted @ 2022-05-11 20:53  桂素伟  阅读(60)  评论(0编辑  收藏  举报