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. 为自定义属性赋值