我有一个非常简单的类:
public class MyCustomBoolean {
private bool _value = false;
public MyCustomBoolean(bool value) {
_value = value;
}
public bool value => _value;
#region casting support
public static explicit operator string(MyCustomBoolean m) {
return m.value.ToString();
}
public static explicit operator bool(MyCustomBoolean m) {
return m.value;
}
#endregion
}
现在,在我的代码中的某处,我尝试:
public void someMethod(MyCustomBoolean param) {
string testString = param;
}
我不断收到的错误是:
无法将源类型 MyCustomBoolean 转换为类型字符串
我有几个处理不同类型的类,但这是唯一给我带来麻烦的类。
我在这里做错了什么?
最佳答案
您正试图将 explicit
运算符用作 implicit
运算符。
以下应该有效:
public void someMethod(MyCustomBoolean param) {
string testString = (string)param; // explicit cast to string
}
如果您想按照编写的方式使用代码,则需要将转换运算符定义为隐式
,如下所示:
public static implicit operator string(MyCustomBoolean m) {
return m.value.ToString();
}
public static implicit operator bool(MyCustomBoolean m) {
return m.value;
}
此时,您之前的代码将按预期工作。
public void someMethod(MyCustomBoolean param) {
string testString = param; // implicit cast
}
关于c# - 为什么即使创建了显式运算符我也无法将源类型转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55231262/