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)
| 归档时间: |
|
| 查看次数: |
13987 次 |
| 最近记录: |