Java 为什么C对'没有限制;构造函数调用必须是构造函数中的第一个语句';
在java和c#中,我对从构造函数内部调用构造函数有点困惑 当从默认构造函数(第一个语句除外)调用另一个构造函数时,Java显示错误 构造函数调用必须是构造函数中的第一条语句 …但C#允许从构造函数的任何语句调用构造函数 有人能解释一下为什么c#允许从默认构造函数中的任何语句行调用另一个构造函数吗 Java:Java 为什么C对'没有限制;构造函数调用必须是构造函数中的第一个语句';,java,c#,Java,C#,在java和c#中,我对从构造函数内部调用构造函数有点困惑 当从默认构造函数(第一个语句除外)调用另一个构造函数时,Java显示错误 构造函数调用必须是构造函数中的第一条语句 …但C#允许从构造函数的任何语句调用构造函数 有人能解释一下为什么c#允许从默认构造函数中的任何语句行调用另一个构造函数吗 Java: public class A { A() { // this(1);// ->> works fine if written her
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");
}
}
public class A {
public A()
{
Console.WriteLine("Default constructor called");
new A(1);
}
public A(int a)
{
Console.WriteLine("Parametrised constructor called");
}
}
C#:
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");
}
}
public class A {
public A()
{
Console.WriteLine("Default constructor called");
new A(1);
}
public A(int a)
{
Console.WriteLine("Parametrised constructor called");
}
}
您的两个代码示例不一样
对于C#,它应该是:
public class A
{
public A() : this(1)
{
Console.WriteLine("Default constructor called");
}
public A(int a)
{
Console.WriteLine("Parametrised constructor called");
}
}
在您的示例中,您只是创建了
a
的第二个实例。这也适用于Java。您的两个代码示例不一样对于C#,它应该是:
public class A
{
public A() : this(1)
{
Console.WriteLine("Default constructor called");
}
public A(int a)
{
Console.WriteLine("Parametrised constructor called");
}
}
在您的示例中,您只是创建了
a
的第二个实例。这也适用于Java。这两个代码段是不等价的。您也在寻找C语言中的this(1)
(或者base(1)
,可以与Java中的super(1)
进行比较)
您现在正在构造函数中构造一个新对象,该对象在创建后立即超出范围,因为您没有分配它
如果在构造函数体中调用this(1)
,C#将给出相同的错误,因此是的,它们的工作方式相同。在C#中,您甚至不能在构造函数中的任何位置调用this(1)
。它应该这样附加:
public A() : this(1)
{ }
这两个代码段并不相等。您也在寻找C语言中的
this(1)
(或者base(1)
,可以与Java中的super(1)
进行比较)
您现在正在构造函数中构造一个新对象,该对象在创建后立即超出范围,因为您没有分配它
如果在构造函数体中调用this(1)
,C#将给出相同的错误,因此是的,它们的工作方式相同。在C#中,您甚至不能在构造函数中的任何位置调用this(1)
。它应该这样附加:
public A() : this(1)
{ }
如果您将它从
this(1)
更改为newa(1)
,那么您也可以在Java中实现这一点。您的C代码并不像您想象的那样。它只是创建了a
的第二个实例。代码的C#等价物将是public a():this(1){…}
-并且你不能有一个中间语句。即使这个问题以错误的前提开始,我认为保持它的开放性是值得的,因为它可以为其他人澄清这种情况。如果您将它从this(1)
更改为newa(1)
,您的C代码也可以在Java中这样做。您的C代码不会做您认为它做的事情。它只是创建了a
的第二个实例。你的代码的C#等价物是public a():这(1){…}
-你不能有一个中间语句。即使这个问题是从一个错误的前提开始的,我认为还是值得打开它,因为它可以为其他人澄清这种情况