开发者

Can access the Parse methods for a given type based on an instance of Type in C#?

开发者 https://www.devze.com 2023-01-31 15:32 出处:网络
I\'m using a DataTable and assigning columns different types. I have a scenario where I\'m receiving String data and I want to parse it based on the column\'s assigned type, but I can\'t figure out ho

I'm using a DataTable and assigning columns different types. I have a scenario where I'm receiving String data and I want to parse it based on the column's assigned type, but I can't figure out how to get开发者_如何学JAVA to the parse methods.

Is is it possible to access the Type instance's parse methods in a generic way?


You're looking for Convert.ChangeType.


If you are using anything more than basic types (that Convert.ChangeType handles quite nicely), the preferred way of doing this is via the TypeConverter:

var converter = TypeDescriptor.GetConverter(type);
object val = converter.ConvertFromString(s); // note various overloads,
                                             // or ConvertFromInvariantString

This is convenient because this model can be extended to recognise additional types (or change the implementation for existing types), both at compile-time (adding [TypeConverter(...)]) or at run-time (TypeDescriptor.AddAttributes(...)).

0

精彩评论

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