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";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值