感谢 Patryk 的评论,我尝试使用 ExpandoObject 并让它像这样工作:
dynamic viewData = new ExpandoObject();
viewData.@class = cssClasses;
if (controlId != null)
viewData.id = controlId;
if (title != null)
viewData.title = title;
// put the result into a route value dictionary so that MVC's EditorFor (etc) can interpret it
var additionalViewData = new RouteValueDictionary(viewData);
最后一行是让它在 MVC 中工作的关键,以便它可以作为 EditorFor 等中的 AdditionalViewData 参数传递。
在我被传递一个匿名类并且需要自己添加到它的情况下,我正在使用反射(并利用 ExpandoObject 实现 IDictionary)。这是我编写的用于检查它是否有效的单元测试:
[TestMethod]
public void ShouldBeAbleToConvertAnAnonymousObjectToAnExpandoObject()
{
var additionalViewData = new {id = "myControlId", css = "hide well"};
dynamic result = new ExpandoObject();
var dict = (IDictionary<string, object>)result;
foreach (PropertyInfo propertyInfo in additionalViewData.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
dict[propertyInfo.Name] = propertyInfo.GetValue(additionalViewData, null);
}
Assert.AreEqual(result.id, "myControlId");
Assert.AreEqual(result.css, "hide well");
}