我有以下代码:
public int Number(int x)
{
return x > 0 ? x : throw new Exception();
}
目标很简单,操作员'?'我想检查一些值,如果它满足条件返回该值,如果不是 - 抛出一些错误。 但VS Intellisense说:无效的表达式throw;我被迫使用其他运营商吗?
P.S。我想它与return throw new Exception();
相同但仍然要确定。
答案 0 :(得分:7)
改为写下:
public int Number(int x)
{
if(x <= 0) throw new Exception();
return x;
}
条件运算符需要返回一个公共基类型,但int
和Exception
没有。特别是投掷与返回相同的东西,即使你的方法返回 Exception
(这很奇怪)这是不可能的。
来自MSDN:
first_expression和second_expression的类型必须相同,或者从一种类型到另一种类型必须存在隐式转换。
答案 1 :(得分:6)
您可以在C#7中执行此操作。您的方法可以进一步缩小为:
public int Number(int x) => x > 0 ? x : throw new Exception();
答案 2 :(得分:5)
在C#7.0之前,如果你想从表达式主体中抛出异常,你必须:
{
"status": "ok",
"count": 2,
"count_total": 2,
"pages": 1,
"posts": [
{
"id": "9",
"type": "post",
"slug": "e5t-hal-3al2a",
"url": "https:\/\/mahdii.000webhostapp.com\/?p=9",
"status": "publish",
"title": "e5t hal 3al2a",
"title_plain": "e5t hal 3al2a",
"date": "2017-02-09 19:35:05",
"modified": "2017-02-09 19:35:05",
"excerpt": "",
"parent": "0",
"category": [
{
"term_id": 1,
"name": "Uncategorized",
"slug": "uncategorized",
"term_group": 0,
"term_taxonomy_id": 1,
"taxonomy": "category",
"description": "",
"parent": 0,
"count": 1,
"filter": "raw",
"cat_ID": 1,
"category_count": 1,
"category_description": "",
"cat_name": "Uncategorized",
"category_nicename": "uncategorized",
"category_parent": 0
}
],
"tag": [
],
"author": [
{
"id": "1",
"slug": "mahdi",
"name": "mahdi",
"first_name": "",
"last_name": "",
"nickname": "mahdi",
"url": "",
"description": "",
"gravatar": "http:\/\/www.gravatar.com\/avatar\/b2f7652b7fd5e51e1ac71f6d23998c4c?s=100&d=mm&r=g"
}
],
"comment_count": "0",
"comment_status": "open"
},
{
"id": "2",
"type": "page",
"slug": "sample-page",
"url": "https:\/\/mahdii.000webhostapp.com\/?page_id=2",
"status": "publish",
"title": "Sample Page",
"title_plain": "Sample Page",
"date": "2017-02-09 12:31:52",
"modified": "2017-02-09 12:31:52",
"excerpt": "This is an example page. It's different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with … <a href=\"https:\/\/mahdii.000webhostapp.com\/?page_id=2\"> Continue reading <span class=\"meta-nav\">→<\/span><\/a>",
"parent": "0",
"category": [
],
"tag": [
],
"author": [
{
"id": "1",
"slug": "mahdi",
"name": "mahdi",
"first_name": "",
"last_name": "",
"nickname": "mahdi",
"url": "",
"description": "",
"gravatar": "http:\/\/www.gravatar.com\/avatar\/b2f7652b7fd5e51e1ac71f6d23998c4c?s=100&d=mm&r=g"
}
],
"comment_count": "0",
"comment_status": "closed"
}
]
}
在C#7.0中,上面现在简化为:
return x > 0 ? x : new Func<int>(() => { throw new Exception(); })();
答案 3 :(得分:-1)
if(x > 0) return x
throw new Exception();