How to cast implicitly on a reflected method call

前端 未结 3 896
我寻月下人不归
我寻月下人不归 2021-02-18 13:08

I have a class Thing that is implicitly castable from a string. When I call a method with a Thing parameter directly the cast from s

3条回答
  •  执笔经年
    2021-02-18 13:55

    The trick is to realize that the compiler creates a special static method called op_Implicit for your implicit conversion operator.

    object arg = "foo";
    
    // Program.showThing(Thing t)
    var showThingReflected = GetType().GetMethod("showThing");
    
    // typeof(Thing)
    var paramType = showThingReflected.GetParameters()
                                      .Single()
                                      .ParameterType; 
    
    // Thing.implicit operator Thing(string s)
    var converter = paramType.GetMethod("op_Implicit", new[] { arg.GetType() });
    
    if (converter != null)
        arg = converter.Invoke(null, new[] { arg }); // Converter exists: arg = (Thing)"foo";
    
    // showThing(arg)
    showThingReflected.Invoke(this, new[] { arg });
    

提交回复
热议问题