无法隐式转换类型'X'到'字符串' - 何时以及如何决定它"不能"? [英] Cannot implicitly convert type 'X' to 'string' - when and how it decides that it "cannot"?

查看:97
本文介绍了无法隐式转换类型'X'到'字符串' - 何时以及如何决定它"不能"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我与的Guid 取值有它。

我当然记得,在整个代码一些地方这种隐式转换工作,在别人没有。到现在为止我看不出的格局。

I certainly remember that throughout the code in some places this implicit conversion works, in others it does not. Until now I fail to see the pattern.

编译器如何确定时,可以不?我的意思是,类型的方法 Guid.ToString()的存在,是不是叫每当需要这种转变?

How the compiler decides when it cannot? I mean, the type method Guid.ToString() is present, isn't it called whenever this transformation is needed?

有人能告诉我在什么情况下这种转换是自动完成的,当我要叫 myInstance.ToString()明确?

Can someone please tell me under what circumstances this transformation is done automatically and when I have to call myInstance.ToString() explicitly?

推荐答案

在短期,当有定义的隐性或显性的转换操作符:

In short, when there is an implicit or explicit conversion operator defined:

class WithImplicit {
    public static implicit operator string(WithImplicit x) {
        return x.ToString();}
}
class WithExplicit {
    public static explicit operator string(WithExplicit x) {
        return x.ToString(); }
}
class WithNone { }

class Program {
    static void Main() {
        var imp = new WithImplicit();
        var exp = new WithExplicit();
        var none = new WithNone();
        string s1 = imp;
        string s2 = (string)exp;
        string s3 = none.ToString();
    } 
}

这篇关于无法隐式转换类型'X'到'字符串' - 何时以及如何决定它"不能"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆