How to convert string to any type

后端 未结 3 2002
暗喜
暗喜 2020-12-05 09:25

I want to convert a string to a generic type

I have this:

string inputValue = myTxtBox.Text;    

PropertyInfo propInfo = typeof(MyClass).GetProperty         


        
相关标签:
3条回答
  • 2020-12-05 09:58
    using System.ComponentModel;
    
    TypeConverter typeConverter = TypeDescriptor.GetConverter(propType);
    object propValue = typeConverter.ConvertFromString(inputValue);
    
    0 讨论(0)
  • 2020-12-05 10:04

    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 讨论(0)
  • 2020-12-05 10:08

    Try Convert.ChangeType

    object propvalue = Convert.ChangeType(inputValue, propType);
    
    0 讨论(0)
提交回复
热议问题