构造函数带有this和base的作用

        #region "Constructor"
/// <summary>
/// 构造函数
/// </summary>
public NavigationUrl()
: this(string.Empty, string.Empty, string.Empty, BtnType.Href, false)
{

}

/// <summary>
/// 重载构造函数
/// </summary>
/// <param name="bText">按钮的文字</param>
/// <param name="bUrl">按钮的javascript/vbscript的Onclick字符</param>
/// <param name="bHint">按钮提示信息</param>
/// <param name="bType">按钮链接类型</param>
/// <param name="bDefault">是否默认选中当前按钮</param>
public NavigationUrl(string bText, string bUrl, string bHint, BtnType bType, bool bDefault)
{
_btnText = bText;
_btnUrl = bUrl;
_btnHint = bHint;
_btnType = bType;
_btnDefaultSelect = bDefault;
}
#endregion

 base是调用基类的构造方法,而this是调用类自身的构造方法。

上面的例子中,当调用第一个构造函数时,执行完继续执行第二构造函数。

 

构造函数中base与this的区别:

namespace ConsoleApplication1
{
class A
{
private int x;

public A()
{
Console.WriteLine("this is class A no arg here, value:{0}", x);
}

public A(int i)
{
x = i;
Console.WriteLine("this is class A one arg here, value:{0}", x);
}
}

class B : A
{
private int y;

public B()
{
y = 1;
Console.WriteLine("this is class B no arg here, value:{0}", y);
}

public B(int i)
{
y = i;
Console.WriteLine("this is class B one arg here, value :{0}", y);
}

public B(int i, int b)
: base(i)
{
y = b;
Console.WriteLine("this is class B two arg here, value:{0}", y);
}
}

class Program
{
static void Main(string[] args)
{
B s = new B(5, 8);
Console.ReadLine();
}
}
}

上面例子输出的结果是:

this is class A one arg here, value:5

this is class B two arg here, value:8

如果把base换成this, 结果是:

this is class A no arg here, value:0

this is class B one arg here, value:5

this is class B two arg here, value:8

可见:base是调用基类的构造方法,而this是调用类自身的构造方法。如果用base的时候调用的不是基类无参构造函数,那么在初始化的时候基类中的无参构造函数也会自动初始化。

posted @ 2011-10-27 14:00  冒牌工程师  阅读(640)  评论(0编辑  收藏  举报