Here is the code:
class Class1
{
private Class2 object;
public Class1(Class2 obj) : this(obj.ToString())
{
this.object = obj;
}
}
More specifically, what does the : this
part do.
Here is the code:
class Class1
{
private Class2 object;
public Class1(Class2 obj) : this(obj.ToString())
{
this.object = obj;
}
}
More specifically, what does the : this
part do.
这:this(obj.ToString)
会导致使用字符串参数定义的构造函数的构造函数代码首先运行。一旦它运行,就会执行构造函数代码(设置this.object = obj
)。
这在MSDN 的构造函数页面(最后一个示例集)中有所介绍。
请注意,在您上面的代码中,如所写,这将导致编译器错误。 您还需要有如下构造函数:
public Class1(string str) // Constructor taking a string, though it could be non-public
{
// Do something with str
}
有了这个构造函数,它将被调用,执行它的初始化步骤,然后第一个构造函数(设置this.object
)将运行。
: this(obj.ToString())
calls overloaded version of constructor from same class.
It means that somewhere in this class you have another constructor which takes string
as parameter and will be executed alongside current constructor.
class A
{
public A(Class2 obj): this(obj.ToString()) // execute A(string text)
{
// your code
}
public A(string text)
{
// your code
}
}
类 1 将有另一个接受字符串参数的构造函数。
它调用与该语法匹配的构造函数。在您的情况下,我假设有一个构造函数在某处接受字符串参数:
public Class1(string s)
{
}