gpt4 book ai didi

java - 为什么C#对 'Constructor call must be the first statement in a constructor'没有限制

转载 作者:太空宇宙 更新时间:2023-11-03 17:14:19 26 4
gpt4 key购买 nike

<分区>

我对在 java 和 c# 中从构造函数内部调用构造函数有点困惑。

当从默认构造函数而不是第一条语句调用另一个构造函数时,Java 显示错误

Constructor call must be the first statement in a constructor

...但是 C# 允许从构造函数的任何语句调用构造函数。

有人能弄清楚为什么 c# 允许从默认构造函数中语句的任何行调用另一个构造函数吗?

Java:

public class A { 
A()
{
// this(1);// ->> works fine if written here
System.out.println("1");
this(1); //Error: Constructor call must be the first statement in a constructor
}
A(int a)
{
System.out.println("2");
}
}

C#:

public class A { 
public A()
{
Console.WriteLine("Default constructor called");
new A(1);
}
public A(int a)
{
Console.WriteLine("Parametrised constructor called");
}
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com