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

问题描述 投票:0回答:4

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

我有这个:

string inputValue = myTxtBox.Text;    

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

object propValue = ?????

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

谢谢

c# generics reflection
4个回答
125
投票
using System.ComponentModel;

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

16
投票

尝试Convert.ChangeType

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

3
投票

我真的不认为我理解你想要实现的目标,但是..你的意思是动态铸造?像这样的东西:

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

干杯。


0
投票
string inputValue = myTxtBox.Text;    

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

propInfo.SetValue(myObject, Convert.ChangeType(inputValue, propType));

这里“myObject”是“MyClass”类的一个实例,您要为其设置通用属性值。

© www.soinside.com 2019 - 2024. All rights reserved.