您需要自己实现PropertyDescriptor
类覆盖GetValue
方法。TypeDescriptor.CreateProperty
因此,您将使用 newMyCoolPropertyDescriptor(dictionary, kvp.Key)
或 like代替。
以下是如何实现它的示例:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace ConsoleApplication1
{
internal sealed class MyCoolPropertyDescriptor : PropertyDescriptor
{
private Func<object, object> propertyGetter;
private Action<object, object> propertySetter;
public MyCoolPropertyDescriptor(
string name,
Func<object, object> propertyGetter,
Action<object, object> propertySetter)
: base(name, new Attribute[] {})
{
this.propertyGetter = propertyGetter;
this.propertySetter = propertySetter;
}
public override bool CanResetValue(object component)
{
return true;
}
public override System.Type ComponentType
{
get { return typeof(object); }
}
public override object GetValue(object component)
{
return this.propertyGetter(component);
}
public override bool IsReadOnly
{
get { return false; }
}
public override System.Type PropertyType
{
get { return typeof(object); }
}
public override void ResetValue(object component)
{
this.propertySetter(component, null);
}
public override void SetValue(object component, object value)
{
this.propertySetter(component, value);
}
public override bool ShouldSerializeValue(object component)
{
return false;
}
}
public sealed class Info : CustomTypeDescriptor
{
IDictionary<string, object> properties;
public Info(IDictionary<string, object> properties)
{
this.properties = properties;
}
public override PropertyDescriptorCollection GetProperties()
{
var orig = base.GetProperties();
var newProps = this.properties
.Select(kvp => new MyCoolPropertyDescriptor(
kvp.Key,
o => ((Info)o).properties[kvp.Key],
(o, v) => ((Info)o).properties[kvp.Key] = v));
return new PropertyDescriptorCollection(orig
.Cast<PropertyDescriptor>()
.Concat(newProps)
.ToArray());
}
}
internal class Program
{
private static void Main(string[] args)
{
var info = new Info(new Dictionary<string, object>{{"some_property", 5}});
var prop = TypeDescriptor.GetProperties(info)["some_property"];
var val = prop.GetValue(info); //should return 5
Console.WriteLine(val);
}
}
}