c# - 如何制作 If 语句来检查 textBox1.Text 是否包含字符串 reply = client.DownloadString (address);适本地?

标签 c# forms winforms visual-studio

我正在尝试制作一个按钮,用于检查 textBox1.Text 是否包含在线 Pastebin 上我的原始文本文件中的任何文本以用于测试目的。

这是我的代码:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        WebClient client = new WebClient();
        string reply = client.DownloadString("https://pastebin.com/raw/0FHx1t5w");
    }

还有我的按钮

private void button1_Click(object sender, EventArgs e)
{
    string textbox = textBox1.Text;

    // Compile error on next line: 
    if (textbox.Contains(reply))
    {
    }
}

字符串 reply 被标记为红色并表示:

The name 'reply' does not exist in the current context

是不是因为.Contains不支持字符串检查?

最佳答案

这是一个范围问题。 reply 是在 Form1 的构造函数中定义的。一旦构造函数退出,reply 变量就不再有效。

您可以在类级别而不是在方法中声明变量。

public partial class Form1 : Form
{
    // Declare it here
    private string reply;

    public Form1()
    {
        InitializeComponent();

        WebClient client = new WebClient();
        reply = client.DownloadString("https://pastebin.com/raw/0FHx1t5w");
    }
}

然后您将能够从按钮单击事件处理程序访问它。

关于c# - 如何制作 If 语句来检查 textBox1.Text 是否包含字符串 reply = client.DownloadString (address);适本地?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49906755/

相关文章:

php - echo Javascript 出现在警报中而不是处理中

forms - 使用分类术语集打开节点/添加表单,不需要用户更改

c# - 在点击事件中识别发件人按钮控件

c# - 网站在移动到新服务器后出现 SQL 错误。

javascript - 避免在 Vue.js 中对变量进行数据绑定(bind)

c# - 无法在我的机器上运行特定的 ASP.NET 项目。 Rider 和 VS2019

c# - 在 TreeView 中有选择地显示复选框(Windows 窗体)

html - 在 WebBrowser WPF 中查看启用 MVC 防伪造的网页

c# - 第二次打开表单时处理的控件

c# - 为什么 int 和 uint 比较在一种情况下失败,而在另一种情况下却没有?