今天太晚了,費話少說,直接上源碼
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的執行個體