开发者

Converting string to a simple type

.Net framework contains a great class named Convert that allows conversion between simple types, DateTime type and String type. Also the class support conversion of the types implementing IConvertible interface.

The class has been implemented in the very first version of .Net framework. There were a few things in the first .Net framework that were not done quite right. For example .Parse methods on simple types would throw an exception if the string couldn't be parsed and there would be no way to check if exception is going to be thrown in advance.

A future version of .Net Framework removed this deficiency by introducing the TryParse method that resolved this problem.

The Convert class dates back to time of the old Pa开发者_Go百科rse method, so the ChangeType method on this class in implemented old style - if conversion can't be performed an exception is thrown.

Take a look at the following code:

public static T ConvertString<T>(string s, T @default)
{
    try
    {
        return (T)Convert.ChangeType(s, typeof(T), CultureInfo.InvariantCulture);
    }
    catch (Exception)
    {
        return @default;
    }            
}

This code basically does what I want. However I would pretty much like to avoid the ugly try/catch here. I'm sure, that similar to TryParse, there is a modern method of rewriting this code without the catch-all. Could you suggest one?


There is no such method, and there never will be.

Convert.Change calls the IConvertible implementation of the object that you pass it to perform the conversion.

Since the IConvertible interface does not define TryConvertTo methods, it is not possible to write a TryConvertTo method. (Adding new methods to IConvertible would be a major breaking change)

It would be possible for Microsoft to create a ISafeConvertible interface with additional methods, but I don't think they will.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜