隐式转换必须明确使用

时间:2017-11-19 02:45:35

标签: c# unity3d struct nullable implicit-conversion

我有一个结构,声明了以下运算符:

public struct myStruct {
    public static implicit operator int(Nullable<myStruct> m){
        /*...*/
    }
}

单独使用此运算符可以隐式地将不可为空的结构转换为int,但尝试隐式转换其可空对等结构仍然会引发编译错误:

  

无法将myStruct?类型隐式转换为int。一个明确的   存在转换(你错过了演员吗?)

显然,提到的“显式”运算符实际上是我声明的隐式运算符,完全删除此运算符也会删除明确的运算符。

当谈到可以为空的结构时,为什么我被强制显式地使用这个运算符,即使它被声明为隐式?

修改
所以这里是“完整代码”,剥离了所有不会使编译器错误消失的内容。结构保持字面意义相同,所有新的都是我的测试代码:

using System;

public struct boilDown {
    public static implicit operator int(Nullable<boilDown> s) { return 0; }
} // END Struct

public class Sandbox {
    void Update ()
    {
        boilDown nonNullable = new boilDown ();
        Nullable<boilDown> NullableVersion = new Nullable<boilDown>();

        int MyInt;
        MyInt = nonNullable;        // this work thanks to my operator
        MyInt = NullableVersion;    // But this line requires an explicit cast
    }
}

版本:
你们都在c#版本问题上暗示过我。 我正在使用Unity 2017.1.0f3,而不是.Net,使用Mono 2.0.50727.1433。 (这显然是一个NET3.5等价,但即使他们的实验NET4.6等效也有这个问题。)
我会问他们这个问题并看看他们说了什么。

2 个答案:

答案 0 :(得分:1)

您可以将NullableVersion显式地转换为int,如下所示。

using System;

public struct boilDown {
    public static implicit operator int(Nullable<boilDown> s) { return 0; }
} // END Struct

public class Sandbox {
    static void Main()
    {

    }
    void Update ()
    {
        boilDown nonNullable = new boilDown ();
        Nullable<boilDown> NullableVersion = new Nullable<boilDown>();

        int MyInt;
        MyInt = nonNullable;        // this work thanks to my operator
        MyInt = (int)NullableVersion;    // works now
    }
}

答案 1 :(得分:1)

感谢所有告诉我这段代码应该编译的人 Unity证实这个错误是他们最终的错误。

相关问题