如何使用 Web 客户端获取的值迭代公共常量?

问题描述

我正在编码一些东西,我的指针在 GitHub 存储库中,所以我使用 client.DownloadString("rawgithubEtc.com");来获取它们,但我想用指针创建一个 PUBLIC 变量,所以请求将只完成一次,我试过这个:

public partial class Form1 : Form
{
    WebClient client = new WebClient();
    public string stuff = client.DownloadString("rawgithubetc.com");
    public int speedTimer = 0; public string speed_data;
    Overlay frm = new Overlay();
    public Mem m = new Mem();
    public Form1()
    {
        InitializeComponent();
    }

...但是 Visual Studio 说:

字段初始值设定项不能用于引用字段、方法或非静态属性

..在此处的 .client 中:

public string stuff = client.DownloadString("rawgithubetc.com");

解决方法

不能在另一个字段的初始化表达式中使用一个字段。但是你可以将初始化移动到构造函数体中,一切都会好起来的。

public partial class Form1 : Form
{
    WebClient client = new WebClient();
    public string stuff; /* not allowed to use "client" here */
    public Form1()
    {
        /* using "client" here is perfectly fine */
        stuff = client.DownloadString("rawgithubetc.com");
        InitializeComponent();
    }