我正在将 C++ 程序移植到 C#。我刚开始学习 C#。
在C++中,如果我定义一个带字符串参数的构造函数
class ProgramOption { public: ProgramOptions(const char* s=0); };
然后我可以使用字符串参数代替ProgramOptions,例如
int myfucn(ProgramOption po);
myfunc("s=20;");
我也可以将它用作默认参数,例如,
int myfunc(ProgramOption po=ProgramOption());
不幸的是在 C# 中,即使我有
class ProgramOption { public ProgramOptions(const char* s=0) {...} }
我发现我不能将它用作默认参数,
int myfunc(ProgramOption po=new ProgramOption());
而且我不能在没有显式转换的情况下传递字符串文字,例如
myfunc("s=20");
这在 C# 中是根本不可能的,还是我可以实现一些方法来实现它?谢谢
最佳答案
您需要定义隐式转换运算符。像这样:
class ProgramOption
{
//...
public ProgramOptions(string str = null)
{
//...
if (!string.IsNullOrWhiteSpace(str))
{
/* store or parse str */
//...
}
}
//...
public static implicit operator ProgramOptions(string str)
{
return new ProgramOptions(str);
}
}
然后将允许您拥有这样的功能:
int myfunc(ProgramOption po = null)
{
po = po ?? new ProgramOptions(); //default value
//...
}
然后这样调用它:
myfunc("some text");
关于c# - C#中的隐式类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21635664/