简体   繁体   中英

C# How to call variable from other class

class Class1
    {
        public static string ShowDialog(string text, string caption)
        {
            Form prompt = new Form()
            {
                Width = 500,
                Height = 150,
                FormBorderStyle = FormBorderStyle.FixedDialog,
                Text = caption,
                StartPosition = FormStartPosition.CenterScreen
            };
            Label textLabel = new Label() { Left = 50, Top = 20, Text = text };
            TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
            Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.OK };
            confirmation.Click += (sender, e) => { prompt.Close(); };
            prompt.Controls.Add(textBox);
            prompt.Controls.Add(confirmation);
            prompt.Controls.Add(textLabel);
            prompt.AcceptButton = confirmation;

            string theanswer = textBox.Text;

            return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
        }
    }

So this is my class code, I am looking to call the 'theanswer' variable in another method I have which is in a different class, how do I achieve this?

You don't call variables, you reference them. Calling is reserved for methods.

As others have said in the comments, you cannot reference the variable directly from outside the method, since it is scoped to the method. You can, however, move the variable definition to class scope and expose it as a public property:

class Class1
{
    public static string theanswer { get; private set; }

    public static string ShowDialog(string text, string caption)
    {
        // other code omitted

        theanswer = textBox.Text;
    }
}

That would allow you to do this from a method in another class:

string myString = Class1.theanswer;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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