C# 使用枚举替代if else if

Posted 写个笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 使用枚举替代if else if相关的知识,希望对你有一定的参考价值。

Laravel 使用 when 替代 if-else

Laravel 使用 when 替代 if-else

在未使用 when 方法之前,我们查询数据可能像这样:

public function store(Request $request)
{
    if(!empty($request->title)){
       $where['title'] = $request->title;
    }

    if(!empty($request->key)){
       $where['key'] = $request->key;
    }
        
    $problems = Problem::where($where)->latest()->paginate(8);

    return response()->json(['status_code' => 200, 'data' => $problems]);
}

我们可以使用 when 方法来看看代码:

public function store(Request $request)
{
    $problems = Problem::when(\\request('key',false), function($q, $key){
            $q->where('title', 'like', '%' . $key . '%');
        })->when(\\request('category',false), function($q, $category){
            $q->where('category_id', $category);
        })->latest()->paginate(8);
}

可能看上去不是很优雅,但它强大的功能是传递参数,省去了大量if-else

再来看看 when 源码,你就知道它得运作方式了:

public function when($value, $callback, $default = null)
{
    if ($value) {
       return $callback($this, $value) ?: $this;
    } elseif ($default) {
       return $default($this, $value) ?: $this;
    }

    return $this;
}

这么看是不是就清楚了很多,这种方法也可以应用到其他框架中或自己项目中使用。

以上是关于C# 使用枚举替代if else if的主要内容,如果未能解决你的问题,请参考以下文章

if-else深度优化:巧用状态变更枚举

if-else深度优化:巧用状态变更枚举

切换 if-else 语句的优势

C# 给枚举类型增加一个描述特性

接口参数校验(规避大量if else)

分支结构(if/else,switch选择判断)