我有以下代码:
public int Number(int x)
{
return x > 0 ? x : throw new Exception();
}目标非常简单,使用运算符“?”我想检查一些值,如果它满足条件,返回那个值,如果不满足,就抛出一些错误。但是VS Intellisense说:表达式术语抛出无效;我是否被迫使用其他运算符?
附注:我猜它和return throw new Exception();是一样的,但还是想确认一下。
发布于 2017-02-14 01:27:10
在C# 7.0之前,如果您想从表达式体中抛出异常,则必须:
return x > 0 ? x : new Func<int>(() => { throw new Exception(); })();在C# 7.0中,上述操作现已简化为:
return x > 0 ? x : throw new Exception();发布于 2017-02-14 00:44:10
改为这样写:
public int Number(int x)
{
if(x <= 0) throw new Exception();
return x;
}条件运算符需要返回一个公共基类型,但int和Exception没有。特别是,抛出一些东西并不等同于返回一些东西,所以即使你的方法会返回一个Exception (这很奇怪),这也是不可能的。
来自MSDN:
first_expression和second_expression的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换。
发布于 2017-02-14 00:46:15
您可以在C# 7中做到这一点。您的方法可以进一步简化为:
public int Number(int x) => x > 0 ? x : throw new Exception();https://stackoverflow.com/questions/42209135
复制相似问题