我已经实现了如下课程:
public class Person
{
public int d, e, f;
public Person()
{
}
public Person(int a)
{
}
public Person(int a, int b)
{
new Person(40, 6, 8);
}
public Person(int a, int b, int c)
{
d = a; e = b; f = c;
}
}
public class Program
{
static void Main(string[] args)
{
Person P = new Person(100, 200);
Console.WriteLine("{0},{1},{2}", P.d, P.e, P.f);// it prints 0,0,0
}
}
Run Code Online (Sandbox Code Playgroud)
现在如果我用两个参数创建Person类的实例,我无法设置d,e,f的值,这是因为在第三个构造函数中,Person的一个新对象被一起声明.
所以前一个对象对这个新对象一无所知.
有什么方法可以抓住这个新对象并从那里为d,e,f赋值?
我认为你实际上是在尝试将构造函数链接在一起,以便一个构造函数将参数传递给另一个:
public Person(int a, int b) : this(40, 6, 8)
{
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是你忽略了a,b但是......通常你只是默认一个值,例如
public Person(int a, int b) : this(a, b, 8)
{
}
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅有关构造函数链接的文章.