简体   繁体   English

嵌套隐式运算符

[英]Nested implicit operator

I have a custom class named Optional< T >. 我有一个名为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. 如果定义从A到B以及从B到C的隐式转换,则不存在从A到C的隐式转换,它们同时调用两者。 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. 您需要创建一个单独的用户定义的从A到C的转换,或者进行显式转换以完成转换的一半。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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