Implicit type conversion in C #

I am porting a C ++ program to C #. I just started to learn C #.

In C ++, if I define a constructor with a string parameter

class ProgramOption { public: ProgramOptions(const char* s=0); };

Then I can use the string parameter instead of ProgramOptions, for example

int myfucn(ProgramOption po);
myfunc("s=20;");

I can also use it as a default argument, for example

int myfunc(ProgramOption po=ProgramOption());

Unfortunately, in C # even I have

class ProgramOption { public ProgramOptions(const char* s=0) {...} }

I found that I can not use it as a default argument,

int myfunc(ProgramOption po=new ProgramOption());

and I cannot pass a string literal without explicit conversion, for example

myfunc("s=20");

Is this just not possible in C #, or can I implement some kind of method to make this happen? Thanks

+4
source share
2 answers

You will need to define an implicit casting operator. Something like that:

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");
+6

# ?

, ++, :
void Process (Employee employee, bool bonus = false)
...
# .

:
( ) # 4.0.

Visual # 2010 .... .


- ;
- new ValType(), ValType - , ;
- (ValType), ValType - .

+1

Source: https://habr.com/ru/post/1525843/


All Articles