简体   繁体   English

如何将变量从一个 class 引用到另一个?

[英]How do I reference a variable from one class to another?

I'm new to C# and I can't figure out how to reference the value of a variable from one class to another.我是 C# 的新手,我不知道如何将变量的值从一个 class 引用到另一个。

It's set to when the button is pressed, it'll take the text in the text box and sets that as "alphaask".它设置为按下按钮时,它将获取文本框中的文本并将其设置为“alphaask”。 Then it instances "alphaanswer" which would tell the label to change its text.然后它实例化“alphaanswer”,它会告诉 label 更改其文本。

"alphaanswer" will take the value "alphaQuest" and see if its equal to "bob" which then would change the label. “alphaanswer” 将取值“alphaQuest”,看看它是否等于“bob”,这将改变 label。

ALL I want to know how to set the value of "alphaQuest" from the value of "alphaask" so the string can check it with "alphaanswer"所有我想知道如何从“alphaask”的值中设置“alphaQuest”的值,以便字符串可以用“alphaanswer”检查它

public partial class QuestionTab : Form
{
    public string alphaask = "null";

    public void button1_Click(object sender, EventArgs e)
    {
        // alphabutton
        // Checks if something is in textbox then says bool is true
        bool asked = false;
        if(textBoxAlpha.Text != "")
        {
            alphaask = textBoxAlpha.Text;
            asked = true;
        }

        if(asked==true)
        {

            // If bool is true than instance auxy
            var instance = new Alpha();
            instance.alphaanswer();

        }
    }
}

public class Alpha
{
    string alphaQuest = // <-- I want to make alphaQuest equal to alphaask

    alphaanswer();

    public void alphaanswer()
    {
        if (alphaanswer == bob)
         {
          //change text in label1
         }
        }
    }

Do these changes做这些改变

public partial class QuestionTab : Form
{
    public string alphaask = "null";

    public void button1_Click(object sender, EventArgs e)
    {
        bool asked = false;
        if(textBoxAlpha.Text != "")
        {
            alphaask = textBoxAlpha.Text;
            asked = true;
        }

        if(asked==true)
        {

            // If bool is true than instance auxy
            var instance = new Alpha();
            instance.alphaAnswer(alphaask); 
            //Here you are sending the current value of alphaAsk to the alphaanswer method.
        }
    }
}


public class Alpha
{
    public void alphaAnswer(string alphaAnswer) //This string receives the value you sent
    {
        if (alphaAnswer == "bob")
         {
          //change text in label1
         }
    }
}

make a contractor in class Alpha with String parameter使用字符串参数在 class Alpha 中创建一个承包商

public Alpha(String value)
{
}

then when you call it那么当你调用它时

var instance = new Alpha(alphaask);
instance.show();

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

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