无法将类型void隐式转换为int [英] Cannot implicitly convert type void to int

查看:79
本文介绍了无法将类型void隐式转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为现有项目创建单元测试.

I'm creating a unit test for an existing project.

  • n1 n2 是输入数字
  • op 是主程序中切换情况下的操作数
  • n1 and n2 are input numbers
  • op is operands in a switch case in the main program

问题出在 actual 上.我无法匹配期望值和实际值,因为出现错误无法将void隐式转换为int .

The problem is with actual. I cannot match the expected and actual value because I get the error cannot implicitly convert void to int.

我的单元测试:

[TestMethod()]
public void docalcTest(int actual)
{
    Form1 target = new Form1(); // TODO: Passenden Wert initialisieren

    double n1 = 15; // TODO: Passenden Wert initialisieren
    double n2 = 3; // TODO: Passenden Wert initialisieren
    int op = 2; // TODO: Passenden Wert initialisieren
    int expected = 5;

    actual = target.docalc(n1, n2, op);

    Assert.AreEqual(expected,actual);
}

docalc的代码:

The code for docalc:

public void docalc(double n1, double n2, int op)
{
    result = 0;
    setText("clear");

    switch (op)
    {
        case 1:
            result = n1 + n2;
            break;
        case 2:
            result = n1 - n2;
            break;
        case 3:
            result = n1 * n2;
            break;
        case 4:
            result = n1 / n2;
            break;
    }

    setText(result.ToString());
}

推荐答案

您的方法 target.docalc()是一个空方法,而 actual 是一个int.如编译器所说,您不能将 void 分配给 int .

Your method target.docalc() is a void method, while actual is an int. You can't assign void to an int, as the compiler says.

根据您的评论(您实际上应该只编辑您的问题),您的 docalc()看起来像这样:

According to your comment (you really should just edit your question), your docalc() looks like this:

public void docalc(double n1, double n2, int op) 
{   
    result = 0; 

    ...

    setText(result.ToString());
}

您必须将方法的返回类型更改为 int ,然后返回结果:

You'll have to change the return type of the method to int, and return result:

public int docalc(double n1, double n2, int op) 
{   
    int result = 0; 

    ...

    return result;
}

旁注,为什么要这么做?

Sidenote, why do you do this?

[TestMethod()]
public void docalcTest(int actual)
{
     ...

    actual = ...

将在不带参数的情况下调用测试方法,因此该方法有点用处.您可能需要将其更改为:

The test method will be called without parameters, so it's a bit useless there. You might want to change it to:

[TestMethod()]
public void docalcTest()
{
     ...

    int actual = ...

这篇关于无法将类型void隐式转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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