你的位置:首页 > ASP.net教程

[ASP.net教程]仿Asp.net MVC 的 ViewBag


一.具体实现

public class ViewBag:System.Dynamic.DynamicObject
{
       private Dictionary<string, object> storage = new Dictionary<string, object>();
 
       public override bool TryGetMember(GetMemberBinder binder, out object result)
       {
           if (storage.ContainsKey(binder.Name))
           {
               result = storage[binder.Name];
               return true;
           }
 
           result = null;
           return false;
       }
 
 
       public override bool TrySetMember(SetMemberBinder binder, object value)
       {
           string key = binder.Name;
 
           if (storage.ContainsKey(key))
               storage[key] = value;
           else
               storage.Add(key, value);
 
           return true;
       }
 
       public override string ToString()
       {
           StringBuilder strSb = new StringBuilder();
           foreach (var item in storage)
           {
               strSb.AppendFormat("property {0}:{1} ",item.Key,item.Value);
           }
           return strSb.ToString();
       }
}

 
 
二 使用
 
1. 为自定义属性赋值
     dynamic bag = new ViewBag();
     bag.Property1 ="test";

2.取值
  string propertyValue= bag.Property1;