c# - 为什么即使创建了显式运算符我也无法将源类型转换为字符串?

标签 c# casting

我有一个非常简单的类:

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/

相关文章:

c# - 使用 WebBrowser WPF 控件以编程方式填写一些 Web 表单

ios - 是否可以从 tableView :numberOfRowsInSection? 返回 NSUInteger

c# - 如何使用反射来检索属性?

Android Google Cast 通知禁用

sql-server - 日期添加副作用吗?

casting - 为什么不将 int 分配给 f32 变量编译?

typescript - 避免在 switch 中进行 typescript 转换

c# - 为什么List.Add()不触发属性的Setter?

c# - 如何使用 C# 将 jpg 文件转换为位图?

c# - WebClient.DownloadFileTaskAsync() 实际上永远不会超时吗?