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";
}
}
想要更快更方便的了解相关知识,可以关注微信公众号
****欢迎关注我的asp.net core系统课程****
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524