考虑以下代码:
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.
这篇关于了解 C# 字段初始化要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!