Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我的变量表示它';它从未使用过,但它是?_C# - Fatal编程技术网

C# 我的变量表示它';它从未使用过,但它是?

C# 我的变量表示它';它从未使用过,但它是?,c#,C#,我刚开始使用C#,在过去一周左右的时间里只使用了控制台。我现在已经开始使用VisualStudioIDE应用程序生成器,并且在使用一个非常基本的程序时遇到了问题 private void button1_Click(object sender, EventArgs e) { Random rnd = new Random(); int chance = rnd.Next(1, 10); if (chance < 8) { bool hit =

我刚开始使用C#,在过去一周左右的时间里只使用了控制台。我现在已经开始使用VisualStudioIDE应用程序生成器,并且在使用一个非常基本的程序时遇到了问题

private void button1_Click(object sender, EventArgs e)
{
    Random rnd = new Random();
    int chance = rnd.Next(1, 10);
    if (chance < 8)
    {
        bool hit = true;
    }
    else
    {
        bool hit = false;
    }

    if (hit == true)
    {
        mhealth -= damage;
        textBox1.Text = Convert.ToString(mhealth);
    }
private void按钮1\u单击(对象发送者,事件参数e)
{
随机rnd=新随机();
int chance=rnd.Next(1,10);
如果(机会<8)
{
bool hit=true;
}
其他的
{
bool-hit=false;
}
if(hit==true)
{
mhealth-=损害;
textBox1.Text=Convert.ToString(mhealth);
}

它告诉我从未使用过“hit”,但它不是吗?代码不起作用,我不确定发生了什么,有什么帮助吗?

您需要在
之外声明
bool hit
if else
语句。请查找下面的代码:

    Random rnd = new Random();
    int chance = rnd.Next(1, 10);
    bool hit;
    if (chance < 8)
    {
        hit = true;
    }
    else
    {
        hit = false;
    }

    if (hit == true)
    {
        mhealth -= damage;
        textBox1.Text = Convert.ToString(mhealth);
    }
Random rnd=new Random();
int chance=rnd.Next(1,10);
布尔击中;
如果(机会<8)
{
命中=真;
}
其他的
{
命中=错误;
}
if(hit==true)
{
mhealth-=损害;
textBox1.Text=Convert.ToString(mhealth);
}

Random rnd=new Random();
int chance=rnd.Next(1,10);
布尔命中率=(几率<8);
如果(命中)
{
mhealth-=损害;
textBox1.Text=Convert.ToString(mhealth);
}

这是由于变量的作用域。您在if{}代码块中声明命中(并且再次在else块中声明命中)。因此,在{}作用域块之外,此类命中不可见/不可访问。若要修复此问题,请在启动if块之前仅声明一次命中


回顾编程中的概念。

在c#教程中阅读“范围”时定义变量External if elseRead。作为旁白,您可以使用
bool hit=chance<8
。如果您在大括号内声明一个
bool
,则它仅在大括号内可见。您还可以简化代码,只显示一行:
if(new Random()。下一步(1,10)<8)textBox1.Text=Convert.ToString(mhealth-=damage);
或干脆
bool hit=chance<8;
@UnholySheep也在答案中添加了那段代码:)或干脆
if(hit)
@OlivierJacot Descombes这是一个不错的捕获:)编辑了上面答案中的代码。或者干脆
if(chance<8)
hit
变量有什么意义?
    Random rnd = new Random();
    int chance = rnd.Next(1, 10);
    bool hit = (chance < 8);
    if (hit)
    {
        mhealth -= damage;
        textBox1.Text = Convert.ToString(mhealth);
    }