使用.NET 4,C#在對象實例上獲取自定義屬性的*值*
比方說,我有類Info
,延伸CustomTypeDescriptor
。類Info
的實例有一個<string, object>
對的字典,在運行時加載。
我希望能夠將字典鍵作爲屬性公開(以便Info
的每個實例具有不同的屬性)。屬性的值應該是字典中的相應值。
我抽時間去揭露性質:
public override PropertyDescriptorCollection GetProperties()
{
var orig = base.GetProperties();
var newProps = dictionary.Select(kvp =>
TypeDescriptor.CreateProperty(
this.GetType(),
kvp.key,
typeof(string)));
return new PropertyDescriptorCollection(
orig.Cast<PropertyDescriptor>()
.Concat(newProps)
.ToArray());
}
的問題是,我如何得到他們的價值觀?
var info = new Info(new Dictionary<string, object>{{"some_property", 5}};
var prop = TypeDescriptor.GetProperties(i_info)["some_property"];
var val = prop.GetValue(i_info); //should return 5
我發現得到控制的情況下prop.GetValue()
被稱爲唯一的辦法是重寫GetPropertyOwner(PropertyDescriptor pd)
,但我的理解是,它希望我返回另一個類型具有匹配實(編譯實例)財產。
我想能夠自己編寫屬性的實際實現(對於此示例,返回字典中的鍵與屬性名稱匹配的值)。
這可能嗎?
我認爲可以使用CustomTypeDescriptor獲取動態屬性(儘管我可能會對其進行擴展)。但是,對於'動態'建議+1。我需要學習如何使用它:) –