Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

casting - 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);

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]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...