【问题标题】:Why static implicit operator doesn't work on DynamicObject inherited classes ? And how to fix it?为什么静态隐式运算符不适用于 DynamicObject 继承的类?以及如何解决?
【发布时间】:2014-01-28 13:45:18
【问题描述】:

代码:

public class t : System.Dynamic.DynamicObject
{

    public dynamic Value;

    public static implicit operator t(int value)
    {
        if (value > 100) value = 100;
        t x = new t();
        x.Value = value;
        return x;
    }
}

用法:

dynamic f = new t();
f = 44; // the implicit operator doesn't get called

但是,如果我将 implicit 更改为 explicit 并像 f = (int)44) 一样使用它,则会调用显式运算符。

编辑:我希望我的类从 DynamicObject 继承。

如何解决这个问题?

【问题讨论】:

    标签: c# .net vb.net c#-4.0 c#-3.0


    【解决方案1】:

    你使用:

    dynamic f = new t();  // f has type 'dynamic', no compile-time link between f and type 't'
    f = 44; // the implicit operator doesn't get called
    

    为什么将44 分配给dynamic 类型的变量会通过任何用户定义的运算符转换44?它只是将44(或者更确切地说是一个装箱的44)放入f

    比较:

    t f = new t();
    f = 44;
    

    【讨论】:

    • 是的,你的代码工作正常,但它不允许我这样做f.member = value
    • @Mahdi 那么这里的.member 是什么?您是否需要一个 expando 对象(一个能够神奇地获得您碰巧使用的任何属性的对象)?因为 .NET 有这个。
    • 是的,我需要那个!谢谢!
    【解决方案2】:

    当您设置f = 44; 时,它不会改变对象的。相反,它重新分配了f 变量以指向一个新对象。默认情况下,新对象将是 int,因为它是 int 文字。如果您想创建一个等于44new t 对象,您需要将其转换为该类型,如下所示:

    f = (t)44;
    

    【讨论】:

      猜你喜欢
      • 2011-10-14
      • 2020-01-17
      • 2019-02-06
      • 2010-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2011-05-15
      相关资源
      最近更新 更多