感謝來自Patryk評論我給它使用ExpandoObject一個去得到它的工作是這樣的:
dynamic viewData = new ExpandoObject();
[email protected] = 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");
}
是的,要麼或使用'dynamic'用'ExpandoObject'代替:) –
@PatrykĆwiek呀,真的。我很喜歡ExpandoObject tbh,這很酷。 –
我不明白你爲什麼不在代碼中保留'object'?這兩種匿名類型都是「對象」。 –