无法隐含的转型'X'到'string'-何时和如何决定,它"不能"?
-
09-09-2019 - |
题
现在我有它 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();
}
}
其他提示
没有,没有隐性转换 GUID
要 String
, ,因此,不在任何地方工作,在所有的代码。
它只能在那里有一个明确的转变,但转换可能不是非常可见。例如当你串连串:
string id = "--" + guidValue + " : " + num;
这可能看起来像一个隐含的转换 GUID
要 String
, 但它不是。生成的代码实际上看起来是这样的:
string id = String.Concat(new object[] { "--", guidValue, " : ", num });
所有的操作数铸型 Object
并放置在一个阵列。的 String.Concat
方法,然后电话的 ToString
方法中的每一项阵列,以获得串表示他们。
唯一的地方,你有效不需要叫ToString()自己是当连串。
Guid g;
int i;
string s = "Hello "+g+' '+i;
然后还有一些情况,呼叫的是通过。净框架,例如在 String.格式().
其他比这时,编译器只会转换成一种类型如果是已知是相容(例如基类或实现一个接口或通过一个明确的编码转换操作者)。当您用一个演员和编译器知道的类型不能相容(例如不在同一个继承线,并且不接口),它还说它无法转换。这同样适用于一般类型参数。
不隶属于 StackOverflow