Invoking methods with optional parameters through reflection

后端 未结 5 767
孤独总比滥情好
孤独总比滥情好 2020-11-27 17:07

I\'ve run into another problem using C# 4.0 with optional parameters.

How do I invoke a function (or rather a constructor, I have the ConstructorInfo ob

5条回答
  •  天命终不由人
    2020-11-27 17:17

    All questions disappear as you see your code decompiled:

    c#:

    public MyClass([Optional, DefaultParameterValue("")]string myOptArg)
    

    msil:

    .method public hidebysig specialname rtspecialname instance void .ctor([opt]string myOptArg) cil managed 
    

    As you see, optional parameter is a real separate entity that is decorated with specific attributes and has to be respected accordingly when invoking via reflection, as described earlier.

提交回复
热议问题