- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
这个问题是Cristi Diaconescu's的延伸关于在 C# 中访问 this
的字段初始值设定项的非法性。
这在 C# 中是非法的:
class C
{
int i = 5;
double[] dd = new double[i]; //Compiler error: A field initializer cannot reference the non-static field, method, or property.
}
好的,所以关于为什么这是非法的,除其他外,Eric Lippert 给出了合理的解释。 :
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.
此外,C# 规范非常简单(在一定程度上):
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.
所以我的问题是:“through a simple-name”是什么意思?
是否有其他合法的替代机制?我确信规范中的几乎每个词都有一个非常具体的原因,那么将此特定代码的非法性限制为通过简单名称引用的原因是什么?
编辑:我没有很好地表达我的问题。我不是在询问“simple-name”的定义,我是在询问将非法性限制在特定场景的背后的原因。如果以任何方式引用任何实例成员总是非法的,那么为什么要如此狭隘地指定它呢?如果不是,那么什么机制是合法的?
最佳答案
在一般情况下,不可能确定表达式是否引用正在构造的对象,因此禁止它并要求编译器诊断它是不可能的。考虑
partial class A {
public static A Instance = CreateInstance();
public int a = 3;
public int b = Instance.a;
}
据我所知,使用 FormatterServices.GetUninitializedObject(typeof(A))
创建一个对象是完全有效的,即使这是一个可怕的想法,设置 A。实例
,然后调用构造函数。当 b
被初始化时,对象读取它自己的 a
成员。
partial class A {
public static A CreateInstance() {
Instance = (A)FormatterServices.GetUninitializedObject(typeof(A));
var constructor = typeof(A).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
var helperMethod = new DynamicMethod(string.Empty, typeof(void), new[] { typeof(A) }, typeof(A).Module, true);
var ilGenerator = helperMethod.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Call, constructor);
ilGenerator.Emit(OpCodes.Ret);
var constructorInvoker = (Action<A>)helperMethod.CreateDelegate(typeof(Action<A>));
constructorInvoker(Instance);
return Instance;
}
}
static class Program {
static void Main() {
Console.WriteLine("A.Instance = (a={0}, b={1})", A.Instance.a, A.Instance.b);
}
}
您只能获得编译时可检测到的编译器错误。
关于c# - 字段初始值设定项访问 'this' 已重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17368447/
我想成为 Spark 纱客户(link)。是否需要安装hadoop?还是只安装 yarn 可以吗? (by this link) 最佳答案 No Spark不需要Hadoop即可运行。 Apache
我是一名优秀的程序员,十分优秀!