简体   繁体   English

C#运营商? 抛出异常

[英]C# Operator ? and throw exception

I have following code: 我有以下代码:

public int Number(int x)
{
    return x > 0 ? x : throw new Exception();
}

The goal is very simple, with operator '?' 目标非常简单,运营商'?' I want to check some value, if it satisfies condition return that value, if not - throw some error. 我想检查一些值,如果它满足条件返回该值,如果不是 - 抛出一些错误。 but VS Intellisense says: Invalid expression term throw; 但VS Intellisense说:无效的表达式throw; Am I forced to use other operators? 我被迫使用其他运营商吗?

PS I guess that it's same as return throw new Exception(); PS我猜它和return throw new Exception(); But still want to be sure. 但还是要确定。

Write this instead: 写这个:

public int Number(int x)
{
    if(x <= 0) throw new Exception();
    return x;
}

The conditional operator needs a common base-type to be returned, but there is none for int and Exception . 条件运算符需要返回一个公共的基类型,但是intException都没有。 In particular throwing something isn´t ment to be the same as returning something so even if your method would return an Exception (which was quite weird) this wouldn´t be possible. 特别是抛出一些东西并不像返回东西一样,即使你的方法会返回一个Exception (这很奇怪),这也是不可能的。

From MSDN : 来自MSDN

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other. first_expression和second_expression的类型必须相同,或者从一种类型到另一种类型必须存在隐式转换。

您可以在C#7中执行此操作。您的方法可以进一步签约:

public int Number(int x) => x > 0 ? x : throw new Exception();

Prior to C# 7.0, if you wanted to throw an exception from an expression body you would have to: 在C#7.0之前,如果要从表达式主体中抛出异常,则必须:

return x > 0 ? x : new Func<int>(() => { throw new Exception(); })();

In C# 7.0 the above is now simplified to: 在C#7.0中,上面现在简化为:

return x > 0 ? x : throw new Exception();

With ? 用? expression both sides must return same type, which is not true in your case. 表达式双方必须返回相同的类型,在您的情况下不是这样。 Replace with if(x > 0) return x throw new Exception(); 替换为if(x > 0) return x throw new Exception();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM