![](/img/trans.png)
[英]PropertyDescriptor.SetValue not working in ModelBinder
[英]How to override PropertyDescriptor.GetValue and PropertyDescriptor.SetValue for dynamic object in .NET 4
您可以簡單地轉換為IDictionary並設置/檢索值,而不是使用該文章的Helper類(已過時)。
public override object GetValue(object component)
{
if (_owner != component) throw new InvalidOperationException("GetValue can only be used with the descriptor's owner.");
//return DynamicHelper.GetValue(component, _propertyName);
return ((IDictionary<String, object>)component)[_propertyName];
}
public override void SetValue(object component, object value)
{
if (_owner != component) throw new InvalidOperationException("SetValue can only be used with the descriptor's owner.");
OnValueChanged(component, EventArgs.Empty);
//DynamicHelper.SetValue(component, _propertyName, value);
((IDictionary<String, object>)component)[_propertyName] = value;
}
編輯:這可能僅適用於ExpandoObjects,這是文章正在使用的..如果您創建自己的動態類具有不同的支持,您可能需要更改它。
您可以使用開源框架Dynamitey,它允許您通過字符串名稱調用任何 IDynamicMetaObjectProvider
的動態屬性。
public override object GetValue(object component)
{
return Dyanmic.InvokeGet(component,propertyName);
}
public override void SetValue(object component, object value)
{
Dyanmic.InvokeSet(component,propertyName, value);
}
它應該是這樣的:
CallSiteContainer.getLengthSite = CallSite<Func<CallSite, object, object>>.Create(Binder.GetMember(CSharpBinderFlags.None,
"Length",
typeof(Program),
new CSharpArgumentInfo[] {
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
}));
和相關的集合將是這樣的:
CallSiteContainer.setLengthSite = CallSite<Func<CallSite, object, object, object>>.Create(Binder.SetMember(CSharpBinderFlags.None,
"Length",
typeof(Program),
new CSharpArgumentInfo[] {
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant | CSharpArgumentInfoFlags.UseCompileTimeType, null)
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.