c# - C#中的隐式类型转换

标签 c# c++

我正在将 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/

相关文章:

c# - 从桌面应用程序 (.Net 2) 调用 WebService (WCF) 时的消息大小

c++ - 在函数/类声明附近编写 C++ 单元测试

c++ - 反序列化中的文件损坏,如何防止崩溃?

c++ - C++ 中的学生 T 分布

c# - 使用已知良好登录访问远程计算机上的 PrincipalContext 时访问被拒绝

c# - 如何在 C# 中的 ffmpeg 中使用管道

c# - C# 中的元组展开类似于 Python

c# - MEF:尽管找到并加载了 PRISM 模块,但应用程序声称找不到它们

c++ - 调试调试和发布版本之间差异的最佳实践和工具?

c++ - 使用 std::iterator traits 和 auto 在函数声明中定义一个函数