原文:http://blog.csdn.net/cabxyz/article/details/41864577
where简单的说就是做范型约束,更多内容参见官方文档:http://msdn.microsoft.com/zh-cn/library/bb384067.aspx
- namespace TestCSharp
- {
- class BaseView
- {
- public int ViewId;
- public string ViewName;
- public string GetInfo()
- {
- return string.Format("viewid:{0},viewName:{1}",this.ViewId,this.ViewName);
- }
- }
- }
- namespace TestCSharp
- {
- class BattleView : BaseView
- {
- public string CityName;
- public int Hp;
- public BattleView()
- {
- this.ViewId = 1;
- this.ViewName = "BattleView";
- }
- }
- }
- namespace TestCSharp
- {
- class LoginView : BaseView
- {
- public string UserName;
- public string Password;
- public LoginView()
- {
- this.ViewId = 0;
- this.ViewName = "LoginView";
- }
- }
- }
- using System;
- namespace TestCSharp
- {
- class ViewFactory<T> where T : BaseView, new()
- {
- private readonly T mView = new T();
- public void Print()
- {
- Console.WriteLine(mView.GetInfo());
- }
- }
- }
- using System;
- using System.Collections;
- using System.Collections.Generic;
- namespace TestCSharp
- {
- class MainClass
- {
- public static void Main(string[] args)
- {
- ViewFactory<LoginView> loginView = new ViewFactory<LoginView>();
- loginView.Print();
- ViewFactory<BattleView> battleView = new ViewFactory<BattleView>();
- battleView.Print();
- //error
- //ViewFactory<Object> createCharView = new ViewFactory<Object>();
- }
- }
- }
上面是约束构造函数,使用 new 运算符创建类型参数的实例。下面我们改造为函数
- using System;
- namespace TestCSharp
- {
- class ViewFactory
- {
- public static void RegView<T>(int viewId, string viewName) where T : BaseView, new()
- {
- T mView = new T {ViewId = viewId, ViewName = viewName};
- Console.WriteLine(mView.GetInfo());
- }
- }
- }
- using System;
- using System.Collections;
- using System.Collections.Generic;
- namespace TestCSharp
- {
- class MainClass
- {
- public static void Main(string[] args)
- {
- ViewFactory.RegView<LoginView>(100,"LoginView");
- ViewFactory.RegView<BattleView>(200, "BattleView");
- }
- }
- }
同样也是创建对象的约束。