一.具體實現
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;{"webroot":"wwwroot","version":"1.0.0-*","dependencies":{"Microsoft.AspNet.Diagnostics":"1.0.0-beta4","Microsoft.AspNet.Mvc":"6.0.0-beta4","Microsoft.AspNet.Mvc.TagHelpers":"6.0.0-beta4","Microsoft.AspNet.Server.IIS":"1.0.0-beta4","Microsoft.AspNet.Server.WebListener":"1.0.0-beta4","Microsoft.AspNet.StaticFiles":"1.0.0-beta4","Microsoft.AspNet.Tooling.Razor":"1.0.0-beta4","Microsoft.Framework.ConfigurationModel.Json":"1.0.0-beta4","Microsoft.Framework.CodeGenerators.Mvc":"1.0.0-beta4","Microsoft.Framework.Logging":"1.0.0-beta4","Microsoft.Framework.Logging.Console":"1.0.0-beta4","Microsoft.VisualStudio.Web.BrowserLink.Loader":"14.0.0-beta4","Microsoft.Framework.ConfigurationModel.UserSecrets":"1.0.0-beta4"},"commands":{"web":"Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000","gen":"Microsoft.Framework.CodeGeneration"},"frameworks":{"dnx451":{},"dnxcore50":{}},"exclude": [ "wwwroot","node_modules","bower_components" ],"publishExclude": [ "node_modules","bower_components","**.xproj","**.user","**.vspscc" ],"scripts":{"postrestore": [ "npm install","bower install" ],"prepare": [ "gulp copy" ] }}