有没有办法为匿名类添加额外的属性(或创建具有额外属性的新实例)?
string cssClasses = "hide"; object viewData = new { @class = cssClasses }; if (suppliedId != null) { // add an extra id property to the viewData somehow... // desired end result is { @id = suppliedId,@class = cssClasses } } // ... code will be passing the viewData as the additionalViewData parameter in asp.mvc's .EditorFor method
解决方法
不,你不能这样做.但是,您可以重新定义它:
dynamic viewData = new { @class = cssClasses }; if (suppliedId != null) { viewData = new { @class = viewData.@class,yourExtra = Property }; }
请注意,我将其更改为动态.这样您就可以编辑属性而无需强制转换为动态.