int的隐式运算符?

Kam*_*mil 3 c# implicit .net-3.5 implicit-conversion

我已经学会了为我的类使用隐式运算符.

现在我想做这样的事情:

public static implicit operator string(int val)
{
    return "The value is: " + val.ToString(); // just an nonsense example
}
Run Code Online (Sandbox Code Playgroud)

但这是错误的.编译说:

用户定义的转换必须转换为封闭类型或从封闭类型转换

我该如何解决这个问题?

我的目标是能够运行这样的代码:

int x = 50;
textbox1.Text = x; // without using .ToString() or casting
Run Code Online (Sandbox Code Playgroud)

Dan*_*rth 6

您不能在运算符的参数或返回类型的类之外添加运算符.
换句话说:您无法添加在两个您无法控制的类型之间进行转换的运算符.

您得到的编译器错误非常明确:

用户定义的转换必须转换为封闭类型或从封闭类型转换

所以,你想要在这里实现的是根本不可能的.
您最好的选择可能是int执行转换并返回a 的扩展方法string.