c# - 如果 Binder 名称为 GetType() 或 ToString() 等,TryInvokeMember 不会触发

标签 c# object dynamic tryinvokemember

我只是在摆弄 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/

相关文章:

c# - SQL Server CE 读取速度慢(1000 行需要 36 秒?)

javascript - JS根据键值循环遍历数组并添加值

c# - 对象实例丢失时如何处理它的引用

javascript - 如何在 VueJs 中动态添加属性

c# - 如何在运行时从类中删除属性

C#:不同位编号方案的左旋算法

c# - MVC3 POST 模型绑定(bind)不适用于特定的复杂模型

c# - Visual Studio 2015,无法更改新资源文件的访问修饰符

javascript - 将对象属性和值转换为字符串

jquery动态绑定(bind).on()选择 parent 还是 child ?