简体   繁体   English

从表单访问main中的实例

[英]accessing an instance in main from a form

/* Hi i am trying to make my first c# application on visual studio. / *嗨,我正在尝试在Visual Studio上制作我的第一个C#应用程序。 I have created a class and an instance of that class in main and i am simply trying to query a member of that instance inside a click event on a form but its telling me the instance name does not exist in the current context. 我已经在main中创建了一个类和该类的实例,而我只是想在表单上的click事件中查询该实例的成员,但是它告诉我实例名称在当前上下文中不存在。 Any help would be appreciated here's my code. 任何帮助将不胜感激,这是我的代码。 */ * /

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;

    namespace WindowsFormsApplication10
    {

     public class character         // this is my class
        {
            public bool hair_black;
        }


        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());

                character deviljin = new character();  // instance of my class

                deviljin.hair_black = true;      // initiating a member of the instance


            }
        }
    }

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace WindowsFormsApplication10
    {


        public partial class Form1 : Form
        {

            int cs1 = 0,cs2=0;


            public Form1()
            {
                InitializeComponent();


            public void pictureBox1_Click(object sender, EventArgs e)
            {

                flowLayoutPanel1.Visible = true;
                if (deviljin.hair_black == true)   // trying to access instance member
                {                                  // but getting deviljin does not
                                                   // exist in the current context
                    pictureBox28.Visible = false;
                }            

            }

        }
    }

Your instance variable deviljin is local to the main method and cannot be directly referenced outside of that method. 您的实例变量deviljin是main方法的局部变量,不能在该方法之外直接引用。

You need to pass the reference inside the instance of Form1 where you are trying to use it. 您需要在要使用它的Form1实例内部传递引用。 This could be done passing the reference directly via the constructor of form1 这可以通过直接通过form1的构造函数传递引用来完成

 Application.Run(new Form1(deviljin));

and of course changing the constructor of Form1 to 当然将Form1的构造函数更改为

private character _devReferenceToCharacterPassed

public Form1(character mycharInstance)
{
    _devReferenceToCharacterPassed = mycharInstance;
    InitializeComponent();
}

now you can use the passed in instance in your click code 现在您可以在点击代码中使用传入的实例

public void pictureBox1_Click(object sender, EventArgs e)
{
    flowLayoutPanel1.Visible = true;
    if (_devReferenceToCharacterPassed.hair_black == true)   
    {                                  
         pictureBox28.Visible = false;
    }            
}

also take note that 还请注意

Application.Run(new Form1(deviljin)); Application.Run(新Form1(deviljin));

is a blocking call. 是一个阻止呼叫。 It means that your code doesn't exit from this call till the Form1 is open, so you need to move the creation of the deviljin variable before the Run call. 这意味着在Form1打开之前,您的代码不会从此调用中退出,因此您需要在Run调用之前将deviljin变量的创建移动。

EDIT: I'm strongly opposed to use of variables with global visibility across an application. 编辑:我强烈反对在整个应用程序中使用具有全局可见性的变量。 Sometimes they are necessary, but they lead to the creation of unmaintainable code very quickly. 有时它们是必需的,但它们会导致很快创建不可维护的代码。 It 'better to learn to program with the fewest possible global variables 学会用尽可能少的全局变量编程

This is because of what the error says - the instance doesn't exist in the current context (the context of the form) 这是由于错误所致-实例在当前上下文(表单的上下文)中不存在

It's a scope issue - every variable you declare has a scope and since you are declaring your character class instance in the local scope of the Main method in the Program class, it will only be visible in that method. 这是一个范围问题-您声明的每个变量都有一个范围,并且由于您是在Program类的Main方法的本地范围内声明字符类实例的,因此该变量仅在该方法中可见。

Since the Program class is static, you could just create a static member on that class eg: 由于Program类是静态的,因此您可以在该类上创建一个静态成员,例如:

namespace WindowsFormsApplication10
{

 public class character         // this is my class
    {
        public bool hair_black;
    }


    static class Program
    {
        public static character deviljin;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

EDIT: didn't really notice this, but as Steve pointed out, whilst this will compile, if you call Application.Run before you instantiate the variable you will get a runtime exception when trying to access it (it will be null) so make sure you do this before Application.Run 编辑:并没有真正注意到这一点,但是正如Steve指出的那样,虽然可以编译,但是如果您在实例化变量之前调用Application.Run,​​则在尝试访问它时将获得运行时异常(它将为null),因此确保在Application.Run之前执行此操作

            deviljin = new character();  // instance of my class

            deviljin.hair_black = true;      // initiating a member of the instance

            Application.Run(new Form1());


        }
    }
}

This way you can access your instance via the Program class: 这样,您可以通过Program类访问实例:

        public void pictureBox1_Click(object sender, EventArgs e)
        {

            flowLayoutPanel1.Visible = true;
            if (Program.deviljin.hair_black == true)   
            { 
                pictureBox28.Visible = false;
            }            

        }

Read up on variable scope, access modifiers and static/instance variables - for a very simple project, static variables can be ok so you can go this route whilst you are still learning 阅读变量范围,访问修饰符和静态/实例变量-对于一个非常简单的项目,可以使用静态变量,因此您可以在学习的同时走这条路

You would need to update your Form to take an instance of Character as a parameter eg 您将需要更新表单以将Character的实例作为参数,例如

public partial class Form1 : Form
{
    private Character _character;
    public Form1(Character character)
    {
        _character = character;
    }

    public void pictureBox1_Click(object sender, EventArgs e)
    {
        If (_character.hair_black)
        {
             ...
        }
    }
}
...
var deviljin = new Character()
{
    hair_black = true
};
Application.Run(new Form1(deviljin));

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM