Winforms - 非静态字段、方法或 属性 需要对象引用
Winforms - An object reference is required for the nonstatic field, method, or property
我正在尝试为我的程序制作 "updater",我需要做的一件事是从 url 下载 exe。我正在尝试使用 WebClient.DownloadFile
(https://msdn.microsoft.com/en-us/library/ez801hhe(v=vs.110).aspx),但出现错误:An object reference is required for the nonstatic field, method, or property 'WebClient.DownloadFile(string, string)'
。我假设这是我忽略的愚蠢行为,但我无法弄清楚。感谢任何帮助。
代码:
private void Update()
{
string downloadURL = EXE_LOCATION;
string progName = Application.ExecutablePath.Substring(Application.ExecutablePath.LastIndexOf("\") + 1);
string progLoc = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\") + 1);
if (File.Exists(progLoc + progName))
{
try
{
File.Move(progLoc + progName, progLoc + "Old-version.exe");
}
catch (Exception ex)
{
Console.WriteLine("Problem renaming: " + ex.Message);
}
}
WebClient.DownloadFile(downloadURL, progLoc + progName);
}
using (var wc = new WebClient())
{
wc.DownloadFile(downloadURL, progLoc + progName);
}
WebClient
只是 class 的名称。您需要对 class 的实例的引用。理解类型、实例、引用和变量之间的区别至关重要;除非这一点得到很好的理解,否则您将很难成为一名高效的程序员。
当我在这里时:取消 File.Exists()
检查。你已经捕捉到了异常。如果文件不存在,就让它来处理问题。
我正在尝试为我的程序制作 "updater",我需要做的一件事是从 url 下载 exe。我正在尝试使用 WebClient.DownloadFile
(https://msdn.microsoft.com/en-us/library/ez801hhe(v=vs.110).aspx),但出现错误:An object reference is required for the nonstatic field, method, or property 'WebClient.DownloadFile(string, string)'
。我假设这是我忽略的愚蠢行为,但我无法弄清楚。感谢任何帮助。
代码:
private void Update()
{
string downloadURL = EXE_LOCATION;
string progName = Application.ExecutablePath.Substring(Application.ExecutablePath.LastIndexOf("\") + 1);
string progLoc = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\") + 1);
if (File.Exists(progLoc + progName))
{
try
{
File.Move(progLoc + progName, progLoc + "Old-version.exe");
}
catch (Exception ex)
{
Console.WriteLine("Problem renaming: " + ex.Message);
}
}
WebClient.DownloadFile(downloadURL, progLoc + progName);
}
using (var wc = new WebClient())
{
wc.DownloadFile(downloadURL, progLoc + progName);
}
WebClient
只是 class 的名称。您需要对 class 的实例的引用。理解类型、实例、引用和变量之间的区别至关重要;除非这一点得到很好的理解,否则您将很难成为一名高效的程序员。
当我在这里时:取消 File.Exists()
检查。你已经捕捉到了异常。如果文件不存在,就让它来处理问题。