当我已经定义了变量时,为什么会收到错误消息,指出我的变量不存在?

编程入门 行业动态 更新时间:2024-10-28 17:27:50
本文介绍了当我已经定义了变量时,为什么会收到错误消息,指出我的变量不存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我收到一个错误,指出 MyRandomArray 在当前上下文中不存在.如何在 C# WinForms 应用程序中跨类访问变量?

I get an error indicating that MyRandomArray doesn't exist in the current context. How do you access variables across classes in a C# WinForms application?

public void Quiz_Load(object sender, EventArgs e)
{
    string[] MyRandomArray = getWordList();
}

private void timer1_Tick(object sender, EventArgs e)
{
    somefunction(MyRandomArray);/// MyRandomArray doesn't exist in the current context.
}

推荐答案

您已经定义了数组,但是Quiz_Load 方法的范围内,因此timer1_Tick 的范围不知道它.如果将其声明为类的实例成员,则可以从任何实例方法访问它:

You've defined the array, but only in the scope of the Quiz_Load method, so the scope of timer1_Tick has no knowledge of it. If you declare it as an instance member of the class, it will be accessible from any instance method:

private string[] MyRandomArray;

public void Quiz_Load(object sender, EventArgs e)
{
    this.MyRandomArray = getWordList();
}

private void timer1_Tick(object sender, EventArgs e)
{
   somefunction(this.MyRandomArray); // No problem
}

进一步阅读

作用域 (C#)

这篇关于当我已经定义了变量时,为什么会收到错误消息,指出我的变量不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 06:58:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1169754.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   当我   不存在   定义   错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!