Spring.net拋磚引玉系列(二)用介面來實現HelloWorld

來源:互聯網
上載者:User

今天太晚了,費話少說,直接上源碼

1.方案總管(Solution Explorer)

2.主要檔案

這裡僅對上一篇中代碼有所變動的地方進行講解。

IHello.cs:新添加了一個介面給主程式調用,這樣主程式就和Hello類解耦了,而此介面具體用什麼類來實現,要通過下面的spring.xml.config設定檔來配置。

IHello.cs
namespace HelloWorld
{
    interface IHello
    {
        void printf(string name);
    }
}

 

spring.xml.config:配置如果傳遞hello1的參數,會構造Hello類的執行個體;如果傳遞hello2的參數,會構造“你好”類的執行個體。

spring.xml.config
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
  <object id="hello1" type="HelloWorld.Hello">
  </object>
  <object id="hello2" type="HelloWorld.你好">
  </object>
</objects>

 

Hello.cs:實現IHello介面的一個類,這個類用英語將Helloworld顯示到控制台。

Hello.cs
namespace HelloWorld
{
    class Hello : IHello
    {

        IHello Members#region IHello Members

        public void printf(string name)
        {
            Console.WriteLine("Hello " + name + "!Welcome to Spring.Net world!");
        }

        #endregion
    }
}

 

你好.cs:實現IHello介面的一個類,這個類用中文將Helloworld顯示到控制台。

你好.cs
namespace HelloWorld
{
    class 你好:IHello
    {
        IHello Members#region IHello Members

        public void printf(string name)
        {
            Console.WriteLine(name + "你好!歡迎來到Spring.Net的世界!");
        }

        #endregion
    }
}

 

Program.cs:主程式,在控制台上分別用英語和中文顯示Helloworld。

Program.cs
using Spring.Context;
using Spring.Context.Support;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            IApplicationContext context = ContextRegistry.GetContext();

            IHello hello1 = (IHello)context.GetObject("hello1");
            hello1.printf("yaoming");

            IHello hello2 = (IHello)context.GetObject("hello2");
            hello2.printf("姚明");

            System.Console.In.Read();
        }
    }
}

 

OK!讓我們運行看看結果:

怎麼樣,簡單吧!好的,別急,最後按例放上源碼:

示範Spring.net用介面來實現HelloWorld的執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.