C# 静态作用域问题

标签 c# wpf oop scope downloadstring

使用 WPF 和 .NET 4.0。

我正在使用 WebClient 下载一些数据,并使用 DownloadStringCompletedEventHandler 在完成时触发我的 DownloadCompletedCallback 函数。

我遇到的问题是,当调用 DownloadCompletedCallback 时,我试图在主窗体上设置标签的内容,但出现错误。

非静态字段、方法或属性“Armory.MainWindow.lblDebug”需要对象引用。

我知道这是因为函数 DownloadCompletedCallback 被声明为静态的,但我不明白为什么这很重要。

这是我正在使用的代码。

public static void DownloadHTML(string address)
{
    WebClient client = new WebClient();

    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadCompletedCallback);

    client.DownloadStringAsync(new Uri(address));
}

private static void DownloadCompletedCallback(Object sender, DownloadStringCompletedEventArgs e)
{
    if (!e.Cancelled && e.Error == null)
    {
        lblDebug.Content = (string)e.Result;
    }
}

最佳答案

I understand that it's because the function DownloadCompletedCallback is declared as static but I don't understand why that matters.

来自 C# 规范:

A method declared with a static modifier is a static method. A static method does not operate on a specific instance and can only directly access static members. A method declared without a static modifier is an instance method.

An instance method operates on a specific instance and can access both static and instance members. The instance on which an instance method was invoked can be explicitly accessed as this. It is an error to refer to this in a static method.

这是因为静态方法不是对象的一部分,所以它们不能与任何对象交互。它们绑定(bind)到没有状态概念的类,因此当您调用它时,静态方法不知道它应该与哪个对象交互的非静态对象变量。

为什么禁止的例子:

Class Example{...}

var ExampleOne = new Example();
var ExampleTwo = new Example();

Example.CallStaticMethod();

那么现在的问题是它应该与哪些非静态变量交互?它应该是 ExampleOne 还是 ExampleTwo,或者它应该只是抛出一个空引用异常。在前两种情况下,系统无法知道它应该与哪个交互,因为您从未指定它(或者它是一个实例方法)。对于第三个,它并不是真正静态的,因为您需要有一个实例来调用它。因此必须禁止访问非静态方法属性等,因为有太多的歧义。

关于C# 静态作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5168788/

相关文章:

c# - 如何加快3个联合表中的选择速度

wpf - 在WPF中,有人动画过网格吗?

c# - 动态选择实体属性?

java - 为什么抽象方法必须由第一个具体类来实现,而不是由链下的一个更远的类来实现?

java - 需要有关概念 "Do Not Repeat Yourself"编码实践的建议

OOP:基于类和基于原型(prototype),还有其他选择吗?

c# - Json.NET C# : JToken. Parent 始终为 null

c# - Oracle.DataAccess.Client 依赖项

c# - ASP.NET DataPager 不保留 QueryString 参数顺序

c# - 如何通过编程调整流文档中的段落间距