我想在访问它之前将属性创建到动态对象中。例如,假设有一个对象 X。在 X 上访问一个不存在的属性“SomeProperty”,如下所示,
var testProperty = X.SomeProperty;
我想在访问时创建 X.SomeProperty。在 C# 动力学中可能吗?
public class X : DynamicObject
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
string name = binder.Name.ToLower();
return dictionary.TryGetValue(name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
dictionary[binder.Name.ToLower()] = value;
return true;
}
}
dynamic obj = new X();
obj.SomeProperty = "Test";
Console.WriteLine(obj.SomeProperty);