访问“this"的字段初始化程序:在 C# 中无效,在 Java 中有效?

Field initializer accessing `this`: invalid in C#, valid in Java?(访问“this的字段初始化程序:在 C# 中无效,在 Java 中有效?)

本文介绍了访问“this"的字段初始化程序:在 C# 中无效,在 Java 中有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码:

class C
{
    int i = 5;
    byte[] s = new byte[i];
}

编译失败,出现以下错误:

fails to compile with the following error:

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

A field initializer cannot reference the nonstatic field, method, or property `C.i'

Resharper 说了类似的话:Cannot access non-static field i in static context.

Resharper says something similar: Cannot access non-static field i in static context.

这符合 C# 规范说 -- 字段初始化器无法访问当前正在创建的实例 (this),或者,通过扩展,任何实例字段:

This is inline with what the C# spec says -- that a field initializer can't access the instance currently being created (this) or, by extension, any of the instance fields:

实例字段的变量初始化器不能引用正在创建的实例.因此,引用是编译时错误this 在变量初始化器中,因为它是一个编译时错误变量初始化器通过 a 引用任何实例成员简单的名字.

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple-name.

然而,这在 Java 中工作得很好:

However, this works just fine in Java:

class C {
    int i = 5;
    byte s[] = new byte[i]; //no errors here
}

还和我在一起吗?好的,这是问题.错误,问题.

在一个假设的世界中,这在 C# 中是有效的,我想知道:它甚至 可能 吗?如果是这样,它会添加到表格中的优点和缺点是什么?此外,由于 Java 确实支持它,是否有相同的优点/缺点 对于 Java?或者两种语言中类型初始化器的工作方式是否存在根本区别?

Still with me? Ok, here's the question. Err, questions.

In a hypothetical world where this would be valid in C#, I'm wondering: would it even be possible? If so, what would be the pros and cons that it would add to the table? Also, since it's really supported by Java, do the same pros/cons hold for Java? Or is there a fundamental difference in the way type initializers work in the two languages?

推荐答案

简而言之,在构造函数主体运行之前访问接收器的能力是边际收益的一个特性,它可以更容易地编写有错误的程序.因此,C# 语言设计者完全禁用了它.如果您需要使用接收器,则将该逻辑放入构造函数主体中.

In short, the ability to access the receiver before the constructor body runs is a feature of marginal benefits that makes it easier to write buggy programs. The C# language designers therefore disabled it entirely. If you need to use the receiver then put that logic in the constructor body.

至于为什么这个特性在 Java 中是合法的,你得问问 Java 设计者.

as for why the feature is legal in Java, you'll have to ask a Java designer.

这篇关于访问“this"的字段初始化程序:在 C# 中无效,在 Java 中有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:访问“this"的字段初始化程序:在 C# 中无效,在 Java 中有效?

基础教程推荐