了解C#字段初始化要求 [英] Understanding C# field initialization requirements

查看:153
本文介绍了了解C#字段初始化要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

public class Progressor
{
    private IProgress<int> progress = new Progress<int>(OnProgress);

    private void OnProgress(int value)
    {
        //whatever
    }
}

在编译时会出现以下错误:

This gives the following error on compilation:


字段初始化程序不能引用非静态字段,方法或属性'Progressor.OnProgress(int)'

A field initializer cannot reference the non-static field, method, or property 'Progressor.OnProgress(int)'

我了解它所抱怨的限制,但是我不明白为什么会这样,但是可以在构造函数中初始化字段,如下所示:

I understand the restriction it is complaining about, but I don't understand why it is an issue, but the field can be initialized in the constructor instead as follows:

public class Progressor
{
    private IProgress<int> progress;

    public Progressor()
    {
         progress =  new Progress<int>(OnProgress);
    }

    private void OnProgress(int value)
    {
        //whatever
    }
}

在C#中,字段初始化与需要此限制的构造方法初始化有什么区别?

What is the difference in C# regarding the field initialization vs constructor initialization that requires this restriction?

推荐答案

字段初始化在基类构造函数调用之前进行,因此它不是有效的对象。此时,以 this 作为参数的任何方法调用都将导致无法验证的代码,如果不允许使用不可验证的代码,则会引发 VerificationException 。例如:在安全透明代码中。

Field initialization come before base class constructor call, so it is not a valid object. Any method call with this as argument at this point leads to unverifiable code and throws a VerificationException if unverifiable code is not allowed. For example: in security transparent code.



  • 10.11.2实例变量初始值设定项

    当实例构造函数没有构造函数初始值设定项,或者它具有形式为base(...)的构造函数初始值设定项时,该构造函数将隐式执行由声明的实例字段的变量初始值设定项指定的初始化。它的班级。这对应于分配的序列,这些分配的序列在输入构造函数之后以及隐式调用直接基类构造函数之前立即执行。变量初始化器按照它们在类声明中出现的文本顺序执行。

  • 10.11.3构造函数执行

    变量初始化器被转换为赋值语句,并在调用基类实例构造函数之前执行这些赋值语句。这种顺序可确保在执行有权访问该实例的任何语句之前,所有实例字段均由其变量初始值设定项初始化。

  • 10.11.2 Instance variable initializers
    When an instance constructor has no constructor initializer, or it has a constructor initializer of the form base(...), that constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor. The variable initializers are executed in the textual order in which they appear in the class declaration.
  • 10.11.3 Constructor execution
    Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed.

这篇关于了解C#字段初始化要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆