如何将字符串转换为任何类型

时间:2010-05-27 16:18:29

标签: c# generics reflection

我想将字符串转换为泛型类型

我有这个:

string inputValue = myTxtBox.Text;    

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

object propValue = ?????

我想将'inputString'转换为该属性的类型,以检查它是否兼容 我怎么能这样做?

tks

3 个答案:

答案 0 :(得分:93)

using System.ComponentModel;

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

答案 1 :(得分:14)

尝试Convert.ChangeType

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

答案 2 :(得分:3)

我真的不认为我理解你想要达到的目标,但是......你的意思是动态的演员?像这样:

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

干杯。

相关问题