将C#编译器执行多个隐式转换从一种类型到另一个? [英] Will the c# compiler perform multiple implicit conversions to get from one type to another?
问题描述
让我们说你有喜欢自己以下的类:
Let's say you have yourself a class like the following:
public sealed class StringToInt {
private string _myString;
private StringToInt(string value)
{
_myString = value;
} public static implicit operator int(StringToInt obj)
{
return Convert.ToInt32(obj._myString);
}
public static implicit operator string(StringToInt obj)
{
return obj._myString;
}
public static implicit operator StringToInt(string obj)
{
return new StringToInt(obj);
}
public static implicit operator StringToInt(int obj)
{
return new StringToInt(obj.ToString());
}
}
请问你再能够编写如下代码
Will you then be able to write code like the following:
MyClass.SomeMethodThatOnlyTakesAnInt(aString);
没有它指出,没有从字符串中没有隐式转换为int?
without it stating that there is no implicit cast from string to int?
[是,我可以测试自己,但我想我会把它在那里,看到所有的大师不得不说]
[Yes, i could test it myself but i thought i would put it out there and see what all of the gurus have to say]
推荐答案
我相当肯定这是不可能在C#3.0。在参考覆盖转换的部分是6.4。也就是说,6.4.4用户定义的隐式转换。
I am fairly certain this is not possible under C# 3.0. The sections in the reference that covers conversions is 6.4. Namely, 6.4.4 "User-defined implicit conversions".
这只是从S-有关转换会谈> T(而不是S-> T-> U)其中覆盖的情况下,如:
It only talks about conversions from S->T (and not S->T->U) which covers the cases such as:
StringToInt _t = "foo";
int t = _t;
和
int t = (StringToInt)"foo";
如果这两种情况下只涉及S-> T(两次)。
Where both of these cases only involve S->T (twice).
我敢肯定这是不可能在C#3.0。
允许S-> T-> U的要求的更多的将由类型匹配完成的工作,至少指定的算法如下。
I am pretty sure this is not possible in C# 3.0. Allowing S->T->U would require much more work to be performed by the type matcher, at least following the algorithm specified.
这篇关于将C#编译器执行多个隐式转换从一种类型到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!