17

现在我和Guids 在一起。

我当然记得,在某些地方的整个代码中,这种隐式转换有效,而在其他地方则无效。直到现在我还没有看到这种模式。

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

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

4

3 回答 3

33

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

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();
    } 
}
于 2009-04-15T11:39:05.277 回答
4

您实际上不需要自己调用 ToString() 的唯一地方是连接字符串时。

Guid g;
int i;
string s = "Hello "+g+' '+i;

然后在某些情况下,调用是由 .NET Framework 进行的,例如在String.Format()中。

除此之外,编译器只会转换已知兼容的类型(例如基类或实现接口或通过显式编码的转换运算符)。当您使用强制转换并且编译器知道类型不兼容时(例如,不在同一继承行中,而不是接口),它也会说它无法转换它。泛型类型参数也是如此。

于 2009-04-15T11:48:20.700 回答
4

不,没有从GUIDto的隐式转换String,因此这在代码中的任何地方都不起作用。

它仅适用于有显式转换的情况,但转换可能不是很明显。例如,当您连接字符串时:

string id = "--" + guidValue + " : " + num;

这可能看起来像是从GUIDto的隐式转换String,但事实并非如此。生成的代码实际上如下所示:

string id = String.Concat(new object[] { "--", guidValue, " : ", num });

所有操作数都转换为类型Object并放置在数组中。然后该方法为数组中的每个项目String.Concat调用该ToString方法以获取它们的字符串表示形式。

于 2009-04-15T11:49:19.807 回答