作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
现在我正在使用 Guid
s。
我当然记得在整个代码中,这种隐式转换在某些地方有效,而在其他地方则无效。直到现在我都看不到模式。
编译器如何决定何时不能?我的意思是,类型方法 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/
我是一名优秀的程序员,十分优秀!