[实例]学习 C# 中的属性

属性是C#从VB.NET语言中借鉴而来的编程技术,所以在刚开始学习时,会觉得与类C风格语言编程习惯不太一样。我们从头(定义变量)开始说起:

如果想要在网页中显示“Hello World!”。我们先来看看如何编写这个程序:

首先,在  ASP.net 的 aspx 文件中写个 label 服务端控件,使它能放置“Hello World”这个值。如下所示:

<asp:Label ID="label1" runat="server" />

 

然后,在相应的 aspx.cs 文件中给上面的 ID 为 label1 的该控件的属性 Text 设值为“Hello World!”。如下所示:

label1.Text = "Hello World!";

 

将上面的代码写在 Page_Load()方法内,这样在 ASP.net 页面载入后,将会在网页中显示该控件的 Text。

这样写的程序虽然你如果只在一个网页中写label 控件的 Text值,但有多个网页都想有label 控件并且都想要放置“Hello World”这个值呢?下面要引入称为“组件”的概念。

我们在开发WebSite这种模式的过程中微软的ASP.net 2.0 框架包含了几个内置的文件夹,其中 App_Code 便是默认放 cs 文件的“组件”用。

在 App_Code 中新建一个名为“HelloWorld”的cs文件,把class(类)用static(静态)作修饰,即静态类。在这个类里面有名为 SayMessage()方法,用于返回“Hello World”这个值。代码如下所示:

public static class HelloWorld
{
public static string SayMessage()
{
return "Hello World!";
}
}

接下来,把 aspx.cs 文件中将Page_Load()中的代码改写为:

label1.Text = HelloWorld.SayMessage();

下面,将HelloWorld.cs改写为:

public static class HelloWorld
{
    private static string _helloworld = String.Empty;

    public static string Helloworld
    {
        get
        {
            _helloworld = "Hello World";
            return _helloworld;
        }
        set
        {
            _helloworld = value;
        }
    }
}

aspx.cs中的代码改写为:

label1.Text = HelloWorld.Helloworld;

上面就是C#属性的应用实例。

posted on 2009-05-08 16:45  豆豆の爸爸  阅读(498)  评论(0编辑  收藏  举报