Will the c# compiler perform multiple implicit conversions to get from one type to another?

一曲冷凌霜 提交于 2019-12-01 18:45:00

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".

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;

and

int t = (StringToInt)"foo";

Where both of these cases only involve S->T (twice).

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.

No C# won't call more than one user defined implicit conversion. From the C# spec section 6.4.3:

Evaluation of a user-defined conversion never involves more than one user-defined or lifted conversion operator. In other words, a conversion from type S to type T will never first execute a user-defined conversion from S to X and then execute a user-defined conversion from X to T.

It does not appear to work. It requires at least one explicit cast. Oh well...

Typos in your snippet:

public 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;
}

If aString is of type StringToInt, your usage should work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!