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

DJP*_*JPB 57 c# generics reflection

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

我有这个:

string inputValue = myTxtBox.Text;    

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

object propValue = ?????
Run Code Online (Sandbox Code Playgroud)

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

TKS

Lee*_*Lee 98

using System.ComponentModel;

TypeConverter typeConverter = TypeDescriptor.GetConverter(propType);
object propValue = typeConverter.ConvertFromString(inputValue);
Run Code Online (Sandbox Code Playgroud)

  • 可能是因为`ChangeType`试图施放,而不是转换.例如,ChangeType不能从`String`变为`Nullable <Int64>` - TypeConverter`可以. (11认同)

SWe*_*eko 14

尝试Convert.ChangeType

object propvalue = Convert.ChangeType(inputValue, propType);
Run Code Online (Sandbox Code Playgroud)

  • 这真是一个评论,而不是问题的答案.请使用"添加评论"为作者留下反馈. (2认同)
  • @SWeko这是通过评论页面进行编辑时的默认回复(这个问题适用于我们两个人).我只是编辑了它. (2认同)