如果在C#中的语句简化 [英] If statement simplification in C#

查看:79
本文介绍了如果在C#中的语句简化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一行代码如下所示:

I have a line of code that looks like this:

if (obj is byte || obj is int || obj is long || obj is decimal || obj is double || obj is float)

这是可能写的东西比这更优雅?是这样的:

Is it possible to write something more elegant than this? Something like:

if (obj is byte, int, long)

我知道,我的例子是不可能的,但有没有办法让这个看起来干净?

I know that my example isn't possible, but is there a way to make this look "cleaner"?

推荐答案

您可以写对象的扩展方法给你的语法如下:

You could write an extension method on object to give you syntax like:

if (obj.Is<byte, int, long>()) { ... }

这样的事情(使用多个版本更少或更多的通用参数:

Something like this (use multiple versions for fewer or more generic arguments:

public static bool Is<T1, T2, T3>(this object o)
{
    return o is T1 || o is T2 || o is T3;
}

这篇关于如果在C#中的语句简化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆