Optional parameters in managed C++/CLI methods

后端 未结 3 1306
感情败类
感情败类 2020-12-10 23:58

How can I declare a managed method in C++/CLI that has an optional parameter when used from C#?

I\'ve decorated the parameter with both an Optional and a DefaultPara

3条回答
  •  暖寄归人
    2020-12-11 00:30

    There is a trick to make this working (workaround). the magic word is nullable, as for nullable types the default is always "null" (.HasValue == false).

    Example:

    C++ CLI in header:

    String^ test([Optional] Nullable boolTest);
    

    C++ CLI in .cpp file:

    String^ YourClass::test(Nullable boolTest)
    {
        if (!boolTest.HasValue) { boolTest = true; }
        return (boolTest ? gcnew String("True") : gcnew String("False"));
    }
    

    to Test it in C#:

    MessageBox.Show(YourClass.test());
    

    Note that [Optional] in the example above is located in the namespace System::Runtime::InteropServices. To access it, add the following line:

    using namespace System::Runtime::InteropServices;
    

提交回复
热议问题