gpt4 book ai didi

c# - 无法将类型 'X' 隐式转换为 'string' - 它何时以及如何决定它 "cannot"?

转载 作者:可可西里 更新时间:2023-11-01 03:04:43 24 4
gpt4 key购买 nike

现在我正在使用 Guids。

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

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

谁能告诉我这种转换在什么情况下会自动完成,以及我什么时候必须显式调用 myInstance.ToString()

最佳答案

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

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();
}
}

关于c# - 无法将类型 'X' 隐式转换为 'string' - 它何时以及如何决定它 "cannot"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/751303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com