代码之家  ›  专栏  ›  技术社区  ›  Sébastien Ros - MSFT

是否可以通过反射调用值类型运算符?

  •  14
  • Sébastien Ros - MSFT  · 技术社区  · 17 年前

    由于C#运算符,例如+、+=、==是可重写的。这让我认为它们是一种方法,因此想知道是否有一种方法可以使用反射来调用它们,例如在Int32上。

    5 回复  |  直到 17 年前
        1
  •  7
  •   Barry Kelly    17 年前

    public T Add<T>(object x, object y)
    {
        return (T)Convert.ChangeType((dynamic)x + (dynamic)y, typeof(T));
    }
    
        2
  •  9
  •   Yuval Itzchakov    11 年前

    add

        3
  •  4
  •   Marc Gravell    17 年前

    泛型 MiscUtil description and examples


    object x = 123, y = 345; // now forget that we know that these are ints...
    object result = Expression.Lambda<Func<object>>(
        Expression.Convert(Expression.Add(
            Expression.Constant(x), Expression.Constant(y)),
        typeof(object))).Compile()();
    
        4
  •  0
  •   Martin Liversage    17 年前

    decimal System.Decimal struct 真实的

    Reflector System.Int32 .

        5
  •  0
  •   Fabrício Matté    17 年前