OneOfT1,…,Tn清新
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                OneOfT1,…,Tn清新
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                OneOf——其中之一,這是一個泛型類,意思就是這里泛型中的任何一個類都可以,還是看代碼吧。
引入包
install-package?OneOf
實(shí)現(xiàn)一個產(chǎn)品查詢,有三種情況,查詢到返回;查詢不到;查詢出錯。
[ApiController][Route("[controller]")]public class HomeController : ControllerBase{private readonly ILogger<HomeController> _logger;public HomeController(ILogger<HomeController> logger){_logger = logger;}[HttpGet("/product/{id}")]public IActionResult Get(int id){OneOf<Product, NotFound, SystemError> result = GetProject(id);return result.Match<IActionResult>(product =>{_logger.LogInformation("查詢成功");return new JsonResult(product);},notfound =>{_logger.LogInformation("沒有查到");return new NotFoundResult();},systemerror =>{_logger.LogError("查詢成敗");return new StatusCodeResult(500);});}/// <summary>/// 按ID查詢產(chǎn)品,有三種返回類型,找到產(chǎn)品返回;按ID查詢不到;查詢過程發(fā)生錯誤/// </summary>/// <param name="id"></param>public OneOf<Product, NotFound, SystemError> GetProject(int id){try{//這里實(shí)現(xiàn)真實(shí)查庫var num = RandomNumberGenerator.GetInt32(1, 10);if (num % 3 == 0){return new NotFound();}else{return new Product() { ID = id, Name = "手機(jī)" };}}catch (Exception exc){_logger.LogCritical(exc, exc.Message);return new SystemError();}}}public class NotFound{}public class SystemError{}public class Product{public int ID { get; set; }public string Name { get; set; }}可以看到,NotFound,SystemError,Product三個類是沒有任何關(guān)系的,是獨(dú)立的類,這里通過OneOf<>,來實(shí)現(xiàn)返回任何類型都可以,按照OOP的思路,需要三個類繼承一個父類來實(shí)現(xiàn),現(xiàn)在用OneOf<>,把這種繼承“解耦”了。
總結(jié)
以上是生活随笔為你收集整理的OneOfT1,…,Tn清新的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 轻量易用的微信Sdk发布——Magico
- 下一篇: 浏览器缓存机制的研究分享
