Convert C++ to C#
I have 2 functions in C++ which need to be converted to C#. Below are the details of the functions
C++
void MyClass::GetArg(string argument, int minError, string* arg1, string* arg2,
string* arg3, string* arg4, string* arg5)
{
if(arg1 != null) *arg1 = GetArg(argument, 1, minError)
if(arg2 != null) *arg2 = GetArg(argument, 2, minError)
if(arg3 != null) *arg3 = GetArg(argument, 3, minError)
if(arg4 != null) *arg4 = GetArg(argument, 4, minError)
if(arg5 != null) *arg5 = GetArg(argument, 5, minError)
}
string MyClass::GetArg(string argument, int argNum, int minError)
{
//Whatever logic
}
And I am seeing function call as
GetArg(argString, 3, &v1, &v2, &v3);
The q开发者_如何学运维uestion I have here is, I am not seeing any overloaded function which takes 5 arguments. Are those additional arguments, arg4 and arg5 optional?
I have created a similar function in C# as below
public string GetArg(string argument, int argNum, int minError)
{
//Logic goes here
}
I have converted GetArg(argString, 3, &v1, &v2, &v3) into 3 separate function calls as below
string v1 = GetArg(argString, 1, 3);
string v2 = GetArg(argString, 2, 3);
string v3 = GetArg(argString, 3, 3);
I am not sure what is the impact of converting as above as I have very minimum knowledge in C++. I would appreciate if anyone could show me a better way of converting this.
Your C++ code won't compile. All argument sare required in C++, unless you specifically make them optional (by using an = default) or by using the variable arguments mechanism leftover from C
As such, it's impossible to make C# do the same thing, since the code you posted is illegal in C++.
You need to pass parameters by reference and use .NET framework 4
using System.Runtime.InteropServices;
public class MyClass {
public string GetArg(string argument, int minError, ref string arg1, ref string arg2, ref string arg3, [Optional] ref string arg4, [Optional] ref string arg5)
{
if(arg1 != null) arg1 = GetArg(argument, 1, minError);
if(arg1 != null) arg2 = GetArg(argument, 2, minError);
if(arg1 != null) arg3 = GetArg(argument, 3, minError);
if(arg1 != null) arg4 = GetArg(argument, 4, minError);
if(arg1 != null) arg5 = GetArg(argument, 5, minError);
}
}
call
GetArg(argString, 3, v1, v2, v3);
精彩评论