我有以下代码:
public int Number(int x)
{
return x > 0 ? x : throw new Exception();
}
Run Code Online (Sandbox Code Playgroud)
目标非常简单,运营商'?' 我想检查一些值,如果它满足条件返回该值,如果不是 - 抛出一些错误.但VS Intellisense说:无效的表达式throw; 我被迫使用其他运营商吗?
PS我猜它是一样的return throw new Exception();但仍然想确定.
写这个:
public int Number(int x)
{
if(x <= 0) throw new Exception();
return x;
}
Run Code Online (Sandbox Code Playgroud)
条件运算符需要返回一个公共基类型,但是没有int和Exception.特别是投掷一些东西并不像返回一样东西,所以即使你的方法会返回一个Exception(这很奇怪),这也是不可能的.
来自MSDN:
first_expression和second_expression的类型必须相同,或者从一种类型到另一种类型必须存在隐式转换.
您可以在C#7中执行此操作.您的方法可以进一步签约:
public int Number(int x) => x > 0 ? x : throw new Exception();
Run Code Online (Sandbox Code Playgroud)
在C#7.0之前,如果要从表达式主体引发异常,则必须:
return x > 0 ? x : new Func<int>(() => { throw new Exception(); })();
Run Code Online (Sandbox Code Playgroud)
在C#7.0中,以上内容现在简化为:
return x > 0 ? x : throw new Exception();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1706 次 |
| 最近记录: |