全局变量不会在一个函数中搜索工作 [英] Global variable won't work in searching in one function

查看:96
本文介绍了全局变量不会在一个函数中搜索工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个计划,pressing按钮1后得到的信息在TextBox1中1和TextBox。
如果您在textbox3输入,如果你写的东西有一样TextBox1中,pressing后按钮2它把TextBox2中的文字在label2.text。

I made a program that gets info in textbox1 and textbox2 after pressing button1. If you type in textbox3 and if what you wrote there is same as textbox1 ,After pressing button2 it puts textbox2's text in the label2.text.

但问题是,它不会把textbox2.text成label2.text。
为什么呢?

But the problem is that it won't put the textbox2.text into label2.text. Why?

这里的code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    ozv[] a = new ozv[5];
    int i = 0;
    private void button1_Click(object sender, EventArgs e)
    {
        a[i] = new ozv();
        a[i].name = textBox1.Text;
        a[i].id = int.Parse(textBox2.Text);
        i++;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        for (int j = 0; j < 5; j++)
        {
            a[j] = new ozv();
            if (a[j].name == textBox3.Text)
            {
                label2.Text = a[j].id.ToString();
            }
        }
    }
}

和这里是我做的类:

类ozv
    {
        公共字符串名称;
        公众诠释身份证;
    }

class ozv { public string name; public int id; }

推荐答案

删除此行:

for (int j = 0; j < 5; j++)
    {
--->    a[j] = new ozv();
        if (a[j].name == textBox3.Text)

您正在擦除你刚刚保存的东西,这就是为什么你没有得到任何结果。

You are erasing what you just saved, this is why you are not getting any result.

此外,检查你[J]实例定义的:

Also, check that you a[j] instance is defined:

if (a[j] != null) && a[j].name == textBox3.Text)

您也可以在突破; 之后,你发现第一个匹配occurence,退出循环较早

You can also break; after you find the first matching occurence, to exit the loop earlier.

注1:你应该尝试去一步一步到code,看着变量状态。这将真正帮助您调试类的东西。

Note 1: you should try going step-by-step into your code, and looking at the variable states. This would really help you debug stuff like that.

注意2:您应该考虑使用列表&LT; ozv&GT; ,这样你可以遍历它,而无需处理空值

Note 2: you should consider using a List<ozv> so that you can just iterate over it without having to handle nulls.

这篇关于全局变量不会在一个函数中搜索工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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