C#:在构造函数中使用它

Raj*_*Rao 4 c# constructor

在C#中可以在构造函数中使用它吗?(即,在构造函数中引用实例是否可以)

举个简单的例子:

public class Test{

 public Test()
 {
    Type type = this.GetType()
 }

}
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 5

是的,您可以this在构造函数中使用,但不能在字段初始值设定项中使用.

所以这是无效的:

class Foo
{
    private int _bar = this.GetBar();

    int GetBar()
    {
        return 42;
    }
}
Run Code Online (Sandbox Code Playgroud)

但这是允许的:

class Foo
{
    private int _bar;

    public Foo()
    {
        _bar = this.GetBar();
    }

    int GetBar()
    {
        return 42;
    }
}
Run Code Online (Sandbox Code Playgroud)