“因为没有隐式转换,所以无法确定".如果返回,则带实习生 [英] "Cannot be determined because there is no implicit conversion" with ternery if return

查看:106
本文介绍了“因为没有隐式转换,所以无法确定".如果返回,则带实习生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果返回,我具有以下带有三元数的ASP.NET Web Api 2操作:

I have the following ASP.NET Web Api 2 action with a ternary if return:

[HttpDelete]
public IHttpActionResult Delete()
{
    bool deleted;

    // ...

    return deleted ? this.Ok() : this.NotFound();
}

我收到

无法确定条件表达式的类型,因为存在 'System.Web.Http.Results.OkResult'和之间没有隐式转换 'System.Web.Http.Results.NotFoundResult'

Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Web.Http.Results.OkResult' and 'System.Web.Http.Results.NotFoundResult'

当它们都实现IHttpActionResult时.

但是如果我删除三元组,编译器会很高兴:

However if I remove the ternary if, the compiler is happy:

if (deleted)
{
    return this.Ok();
}
return this.NotFound();

这是为什么?

推荐答案

您需要将结果显式转换为IHttpActionResult:

You need to explicitly cast the result to IHttpActionResult:

return deleted ? (IHttpActionResult) this.Ok() : this.NotFound();

关于赠款问题:

为什么Sam的第二个代码块没有显式转换为 IHttpActionResult,只是出于好奇吗?这有什么特别之处吗 有条件的?:运算符?

Why does Sam's second block of code work without explicitly casting to IHttpActionResult, just out of curiosity? Is this something particular to the conditional ?: operator?

让我们创建一个简单的演示. 假定以下代码:

Lets create a simple demonstration. Assume the following code:

public interface IFoo { }

public class B : IFoo { }

public class C : IFoo { }

然后是以下内容:

public class A
{
    IFoo F(bool b)
    {
        return b ? (IFoo) new B() : new C();
    }
}

让我们看看编译器如何反编译三元运算符:

Lets see how the compiler de-compiles the ternary operator:

private IFoo F(bool b)
{
    IFoo arg_13_0;
    if (!b)
    {
        IFoo foo = new C();
        arg_13_0 = foo;
    }
    else
    {
        arg_13_0 = new B();
    }
    return arg_13_0;
}

显式强制转换足以使编译器推断变量应为IFoo类型,从而满足我们的整个if-else要求.这就是为什么仅对类型转换一次就提示"编译器就足够了.

The explicit cast is enough for the compiler to infer that the variable should be of type IFoo and hence satisfy our whole if-else. That is why it is enough for us to "hint" the compiler only once of our type cast.

@dcastro引用了语言规范的确切部分,该部分确定了对类型的控制,请参阅该部分以了解教科书的定义.

@dcastro has referenced the exact part of the language specification which determines the control of the type, see that for text-book definition.

这篇关于“因为没有隐式转换,所以无法确定".如果返回,则带实习生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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