簡體   English   中英

如何在.NET 4中覆蓋動態對象的PropertyDescriptor.GetValue和PropertyDescriptor.SetValue

[英]How to override PropertyDescriptor.GetValue and PropertyDescriptor.SetValue for dynamic object in .NET 4

我們使用DynamicObject進行動態屬性創建,但之后我們要使用PropertyGrid來顯示這些屬性並對其進行編輯。

首先,我發現這個文章,而這一個 我嘗試使用第二篇文章代碼,但以更通用的方式,基本上用變量替換所有方法名稱常量。 但問題是VS2010找不到CSharpGetMemberBinder類型。

有人知道如何更換它嗎? 或者最好的方法是什么?

您可以簡單地轉換為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM