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屋!