开发者

Replacement for "TypeDescriptor" class (since it's not implemented on Windows Phone 7)?

I have a really simple function that I wrote about a million years back that tries to convert a string to another type. Works great for values types, numbers, enums, datetimes etc so I use it all the time when parsing xml file values, web request results - whatever.

However my code won't work on the Windows Phone 7 because the "TypeDescriptor" object is not implemented (see the PC code sample below). Any recommendations on how I can implement a really simple string -> type converter on the phone?

Here's my existing code (written for non-phones):

    internal T ChangeType<T>(object o)
    {
       开发者_Python百科 Type typeOfT = typeof(T);

        // null
        if (o == null)
        {
            return default(T);
        }

        // are types the same
        if (typeOfT == o.GetType())
        {
            return (T)o;
        }

        // these are different type - try to see
        // if there's a built in convertor
        // NOTE: "TypeDescriptor" not implemented on Windows Phone 7
        TypeConverter convertor = TypeDescriptor.GetConverter(typeOfT); 
        if (convertor.CanConvertFrom(o.GetType()))
        {
            return (T)convertor.ConvertFrom(o);
        }
        else
        {
            throw new Exception("Can not convert value to type: " + typeOfT.Name);
        }

    }


There's an MSDN article on How to: Implement a Type Converter.

Yes, this is somewhat reinventing the wheel compared to what exists in the full framework. Unfortunately this is a problem we ahve to deal with in the Compact Framework though.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜