Cannot implicitly convert type #39;X#39; to #39;string#39; - when and how it decides that it quot;cannotquot;?(无法将类型“X隐式转换为“字符串——它何时以及如何确定它“不能?)
问题描述
现在我正在使用 Guid
s.
我当然记得,在整个代码中,这种隐式转换在某些地方有效,而在其他地方则无效.直到现在我都看不到这种模式.
I certainly remember that throughout the code in some places this implicit conversion works, in others it does not. Until now I fail to see the pattern.
编译器如何决定什么时候不能?我的意思是,类型方法 Guid.ToString()
是存在的,不是在需要这种转换时调用吗?
How the compiler decides when it cannot? I mean, the type method Guid.ToString()
is present, isn't it called whenever this transformation is needed?
谁能告诉我这种转换是在什么情况下自动完成的,我什么时候必须显式调用 myInstance.ToString()
?
Can someone please tell me under what circumstances this transformation is done automatically and when I have to call myInstance.ToString()
explicitly?
推荐答案
简而言之,当定义了隐式或显式转换运算符时:
In short, when there is an implicit or explicit conversion operator defined:
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();
}
}
这篇关于无法将类型“X"隐式转换为“字符串"——它何时以及如何确定它“不能"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法将类型“X"隐式转换为“字符串"——它何时以及如何确定它“不能"?


基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01