开发者

How to convert string to any type

开发者 https://www.devze.com 2023-01-01 11:52 出处:网络
I want to convert a string to a generic type I have this: string inputValue = myTxtBox.Text; PropertyInfo propInfo = typeof(MyClass).GetProperty(myPropertyName);

I want to convert a string to a generic type

I have this:

string inputValue = myTxtBox.Text;    

PropertyInfo propInfo = typeof(MyClass).GetProperty(myPropertyName);
Type propType = propInfo.PropertyType;

object propValue = ?????
开发者_开发技巧

I want to convert 'inputString' to the type of that property, to check if it's compatible how can I do that?

tks


using System.ComponentModel;

TypeConverter typeConverter = TypeDescriptor.GetConverter(propType);
object propValue = typeConverter.ConvertFromString(inputValue);


Try Convert.ChangeType

object propvalue = Convert.ChangeType(inputValue, propType);


I don't really think I understand what your are trying to archieve, but.. you mean a dynamic casting? Something like this:

 TypeDescriptor.GetConverter(typeof(String)).ConvertTo(myObject, typeof(Program));

Cheers.

0

精彩评论

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