不能隐式地将类型'X'转换为'string' - 何时以及如何判断它"不能"?

Use*_*ser 16 c# tostring type-conversion

现在我用Guids了.

我当然记得,在某些地方的代码中,这种隐式转换是有效的,而在其他地方却没有.直到现在我都没有看到这种模式.

编译器如何决定它何时不能?我的意思是,类型方法Guid.ToString()存在,不需要在需要这种转换时调用它吗?

有人可以告诉我在什么情况下这种转换是自动完成的,当我必须myInstance.ToString()明确调用时?

Mar*_*ell 32

简而言之,当定义了隐式或显式转换运算符时:

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();
    } 
}
Run Code Online (Sandbox Code Playgroud)

  • 只是为自己查找.我不敢相信这些年来我用C#错过了这个东西.我想真的不需要它......感谢让我今天学到新东西. (2认同)