假设我不能使用 ExpandoObject 并且必须像这样滚动我自己的:-
class MyObject : DynamicObject {
dictionary<string, object> _properties = dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result) {
string name = binder.Name.ToLower();
return _properties.TryGetValue(name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value) {
_properties[binder.Name.ToLower()] = value;
return true;
}
}
并且在我拥有的类层次结构中更进一步
class MyNewObject : MyObject {
public string Name {
get {
// do some funky stuff
}
set {
// ditto
}
}
}
这非常好,因为现在我可以执行以下操作:-
dynamic o = MyNewObject();
o.Age = 87; // dynamic property, handled by TrySetMember in MyObject
o.Name = "Sam"; // non dynamic property, handled by the setter defined in MyNewObject
但以上假设我在编译时知道属性(例如年龄、姓名)。
假设直到运行时我才知道它们会是什么。
如何更改上述内容以支持我只会在运行时知道的属性?
基本上我想我要问的是如何调用直接调用 TrySetMember 的代码,以便它要么创建一个新属性,要么在已定义的情况下使用 getter/setter。
最终解决方案如下:-
using System.Dynamic;
using Microsoft.CSharp.RuntimeBinder;
using System.Runtime.CompilerServices;
class MyObject : DynamicObject {
Dictionary<string, object> _properties = new Dictionary<string, object>();
public object GetMember(string propName) {
var binder = Binder.GetMember(CSharpBinderFlags.None,
propName, this.GetType(),
new List<CSharpArgumentInfo>{
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)});
var callsite = CallSite<Func<CallSite, object, object>>.Create(binder);
return callsite.Target(callsite, this);
}
public void SetMember(string propName, object val) {
var binder = Binder.SetMember(CSharpBinderFlags.None,
propName, this.GetType(),
new List<CSharpArgumentInfo>{
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)});
var callsite = CallSite<Func<CallSite, object, object, object>>.Create(binder);
callsite.Target(callsite, this, val);
}
public override bool TryGetMember(GetMemberBinder binder, out object result) {
string name = binder.Name.ToLower();
return _properties.TryGetValue(name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value) {
_properties[binder.Name.ToLower()] = value;
return true;
}
}