简体   繁体   English

我在 C# 上遇到编译器错误你能帮帮我吗?

[英]I get Compiler Error on C# Can you help me?

I am getting an error can you help me我收到一个错误你能帮我吗

Visual Studio says there is a problem with the h in the print part: Visual Studio 说打印部分的 h 有问题:

Error CS0165: Use of unassigned local variable 'h' (CS0165)错误 CS0165:使用未分配的局部变量 'h' (CS0165)

static void Main()
{
    int[ , ] m = new int [8,8];
    int i ;
    int h ;
    Random rnd = new Random();
    for( i = 0 ; i< 8 ; i++)
    {
        for( h = 0 ; h< 8 ; h++)
        {
            m[i,h] = rnd.Next(10);
        }
    }
    Console.WriteLine(m[i,h]);
      
}

Your variables have no assigned values:您的变量没有赋值:

int i ;
int h ;

Now, the compiler knows that i will be assigned a value here:现在,编译器知道i在这里被赋值:

for( i = 0 ; i< 8 ; i++)

Without looking too deep under the hood, basically the i = 0 part is guaranteed to happen whether the loop body executes or not.无需在引擎盖下看得太深,基本上i = 0部分无论循环体是否执行都会保证发生。 Then we know that h will also be assigned a value here:那么我们知道这里也会给h赋值:

for( h = 0 ; h< 8 ; h++)

Because we know that the outer loop will execute at least once, because we know 0 is less than 8. But the compiler isn't as aware of this.因为我们知道外循环至少会执行一次,因为我们知道 0 小于 8。但是编译器并没有意识到这一点。 The compiler follows a simpler set of rules for the guarantees that it makes.编译器遵循一组更简单的规则来保证它。 And those rules do not include executing the program's logic to see if something will or won't happen.而且这些规则不包括执行程序的逻辑以查看是否会发生某些事情。

So the bottom line is that, while the compiler can guarantee that i will be assigned a value, it can not guarantee that h will.所以底线是,虽然编译器可以保证i将被分配一个值,但它不能保证h会。 Hence the error.因此错误。

The simple solution is just to assign values to your variables:简单的解决方案就是为变量赋值:

int i = 0;
int h = 0;

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

相关问题 C# 旋转pictureBox,我想垂直移动总线我不会,你能帮我编码吗? - C# Rotate pictureBox , I want to move the bus vertically and I cant, can you help me of coding? 你能帮我理解这个 C# function 吗? - Can you help me understand this C# function? 我如何在 C# 中执行它有人可以帮助我 - how can i execute this in C# can someone help me 有人可以在C#中帮我解决这个问题吗 - Can someone help me solve this in c# 有人可以在C#中帮助我处理数组吗? - Can someone help me with arrays in c#? 为什么此C#代码具有未声明的get主体构建? 以及如何使编译器对此产生错误? - Why does this C# code with an an undeclared get body build? And how can I make the compiler throw an error on this? 你能帮我在 C# 中创建 4 个从 1 到 10 的唯一数字吗? - Can you help me to create 4 unique numbers from 1-10 in C#? 你能帮我理解一下使用C#闭包的斐波那契的例子吗? - Can you help me understand this example of fibonacci using C# closures? 我可以以某种方式提示编译器在 C# 中为我计算常量表达式吗? - Can I somehow hint the compiler to calculate constant expression for me in C#? 你能帮我解决我收到的错误:“输入字符串的格式不正确吗?” - Can you help me with an error I've been receiving: “input string was not in the correct format?”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM