我只是在摆弄 C# 4.0 动态关键字,并对一件事感到好奇。
假设我有一个类 DynamicWeirdness : DynamicObject
在其中我有一个名为 reference
的字段,它也是 dynamic
类型。还有一个名为 referencetype
的字段,它的类型是 Type
这是我的构造函数:
public DynamicWeirdness(object reference)
{
this.reference = reference;
this.referencetype = reference.GetType();
}
如果我尝试这样做:
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
if (binder.Name == "GetType" && args.Length == 0)
{
result = referencetype;
return true;
}
result = null;
return false;
}
当我调用 DynamicWeirdness
对象的 GetType()
时,它会忽略我的调用并返回 {Name = "DynamicWeirdness"FullName = "Dynamic1.DynamicWeirdness "
。为什么?
我已经尝试使用 ToString()
、GetHashCode()
,同样的事情发生了。
最佳答案
根据documentation for DynamicObject :
You can also add your own members to classes derived from the DynamicObject class. If your class defines properties and also overrides the TrySetMember method, the dynamic language runtime (DLR) first uses the language binder to look for a static definition of a property in the class. If there is no such property, the DLR calls the TrySetMember method.
由于 DynamicObject 继承自 Object,因此 Object 的任何方法都将阻止 TryInvokeMember 处理调用。
关于c# - 如果 Binder 名称为 GetType() 或 ToString() 等,TryInvokeMember 不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7040999/