简体   繁体   中英

Nested implicit operator

I have a custom class named Optional< T >. This class overrides the implicit operator, something like this:

public static implicit operator Optional<T>(T value)
{
    return new Optional<T>(value);
}

public static implicit operator T(Optional<T> value)
{
    return value.value;
}

Ok, till now all fine, the direct operations like these work:

Optional<int> val = 33; //ok
int iVal = val; //ok

But, this doesn't work:

Optional<Optional<int>> val = 33; //error, cannot convert implicitly

So I'm wondering how can be supported the previous case.

Cheers.

You cannot chain user-defined implicit operators. If you define an implicit conversion from A to B, and from B to C, there is no implicit conversion from A to C that calls both. You'll either need to create a separate user-defined conversion from A to C, or have an explicit conversion to do half of the conversion for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM